Scripting >> Python >> Examples >> Input Output >> How to open, read, write and close a file

 

 

Open file with default mode

f = open("test.txt")  # opening a file from current directory
 

f = open("c:/temp/readme.txt") #open by specifying full path

 

Open file with specific mode

 

f = open("test.txt")      # equivalent to 'r' or 'rt'
f = open("test.txt",'w')  # write in text mode
f = open("img.bmp",'r+b') # read and write in binary mode
f = open("test.txt",mode = 'r',encoding = 'utf-8')
 

 

Mode Purpose
r Open for read (default)
w Open for write.
Creates new if not found, Truncates if exists
x Open exclusively for creation.
Fail if file exists
a Open for append
Creates new if not found.
Appends if exist
t Open in text mode (default)
b Open in binary mode
+ Open for updating - both read and write
Close a file

f = open("test.txt",encoding = 'utf-8')
# perform file operations
f.close()

or better

try:
   f = open("test.txt",encoding = 'utf-8')
   # perform file operations
finally:
   f.close()

Write to a file with open("test.txt",'w',encoding = 'utf-8') as f:
   f.write("my first file\n")
   f.write("This file\n\n")
   f.write("contains three lines\n")
Read a file
>>> f = open("test.txt",'r',encoding = 'utf-8')
>>> f.read(4)    # read the first 4 data
'This'

>>> f.read(4)    # read the next 4 data
' is '

>>> f.read()     # read in the rest till end of file
'my first file\nThis file\ncontains three lines\n'

>>> f.read()  # further reading returns empty sting
''
Show current file position >>> f.tell()    # get the current file position
56
Jump to a file position >>> f.seek(0)   # bring file cursor to initial position
0
Read line by line in a for loop

>>> for line in f:
...     print(line, end = '')

# the variable line itself would contain newline \n read from the file
# set the end parameter for print() function to avoid double printing newline

Read only one line f.readline()  # read one line from the current position
Read all lines from current position to end of file

f.readlines()

Returns a list of lines

e.g.
['first line\n','second line\n','third line\n']

full list of file methods

f = open("test.txt",'r+a',encoding = 'utf-8')

f.method :-

Method Description
close() Close an open file. It has no effect if the file is already closed.
detach() Separate the underlying binary buffer from the TextIOBase and return it.
fileno() Return an integer number (file descriptor) of the file.
flush() Flush the write buffer of the file stream.
isatty() Return True if the file stream is interactive.
read(n) Read atmost n characters form the file. Reads till end of file if it is negative or None.
readable() Returns True if the file stream can be read from.
readline(n=-1) Read and return one line from the file. Reads in at most n bytes if specified.
readlines(n=-1) Read and return a list of lines from the file. Reads in at most n bytes/characters if specified.
seek(offset,from=SEEK_SET) Change the file position to offset bytes, in reference to from (start, current, end).
seekable() Returns True if the file stream supports random access.
tell() Returns the current file location.
truncate(size=None) Resize the file stream to size bytes. If size is not specified, resize to current location.
writable() Returns True if the file stream can be written to.
write(s) Write string s to the file and return the number of characters written.
writelines(lines) Write a list of lines to the file.