Link Search Menu Expand Document

Files

Python File I/O

Open Files

f = open('file.txt')

Python File Modes

Mode Description
‘r’ Open a file for reading. (default)
‘w’ Open a file for writing. Creates a new file if it does not exist or truncates the file if it exists.
‘x’ Open a file for exclusive creation. If the file already exists, the operation fails.
‘a’ Open for appending at the end of the file without truncating it. Creates a new file if it does not exist.
‘t’ Open in text mode. (default)
‘b’ Open in binary mode.
’+’ Open a file for updating (reading and writing)
f = open("test.txt")      # equivalent to 'r' or 'rt'
f = open("test.txt", 'w')  # write in text mode
f = open("python.png",'r+b') # read and write in binary mode

File Encodings

Unlike other languages, the character ‘a’ does not imply the number 97 until it is encoded using ASCII (or other equivalent encodings). The default encoding is platform dependent.

  • In Windows it is ‘cp1252’
  • In Linux it is ‘utf-8’

You cannot rely on the default encoding or else our code will behave differently in different platforms. It is highly recommended to specify the encoding type when working with text files.

f = open("file.txt", mode='r', encoding='utf-8')

Closing Files

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

In the last example exceptions could crash your program. Exception handlig is a topic in itself, but here we’ll simply wrap the code in a try…catch block. Now the file handle will be closed regardless of whether or not there was an exception. In the example above, an exeption might result in the file remaining open (and potentially locked) from other applications in the event of an exception.

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

Using with

The best way to ensure that you close your files when the code block terminates is by using the with statement. When using the with statement you do not have to explicitly call the file’s close() method.

with open('file.txt') as f:
    text = f.read()

print(text)
#    f.close() # not necessary
hello class
python is fun

let's get started

Writing Files

with open("file.txt", 'w', encoding='utf-8') as f:
    print(type(f))
    f.write("hello class\n" )
    f.write("python is fun\n\n")
    f.write("let's get started\n")       
<class '_io.TextIOWrapper'>
with open("file.txt", 'w', encoding='utf-8') as f:
    f.write("hello class\npython is fun\n\nlet's get started\n")
!cat file.txt
hello class
python is fun

let's get started

Reading Files

f = open("file.txt", 'r', encoding='utf-8')
print('1:', f.read(3)) # read the 1st 3 characters
print('2:', f.read(3)) # read the next 3 characters
print('3:', f.read()) # read until the end
print('4:', f.read()) # return's an empty string
1: hel
2: lo 
3: class
python is fun

let's get started

4: 
f.tell() # get the current file position
45
f.seek(0) # bring file cursor to initial position
0
f.read() # read the entire file
"hello class\npython is fun\n\nlet's get started\n"
f.seek(0) # reset the cursor
0
# read line by line
for line in f:
    print(line, end='')
hello class
python is fun

let's get started
f.seek(0) # reset the cursor
0
# read line by line
f.readline()
'hello class\n'
f.readline()
'python is fun\n'
f.readline()
'\n'
line = f.readline()
print(type(line), line)
<class 'str'> let's get started
f.readline()
''
f.seek(0) # reset the cursor
0
# read all lines at once
f.readlines()
['hello class\n', 'python is fun\n', '\n', "let's get started\n"]

Some Notes on Printing

print('abcd')
print('efgh')
abcd
efgh
print('abcd', end='')
print('efgh')
abcdefgh
text = '  abcd      '
print(text, end='')
print(text)
  abcd        abcd      
text = '  abcd      '
text = text.strip()
print(text, end='')
print(text)
abcdabcd
str.strip?
Signature: str.strip(self, chars=None, /)
Docstring:
Return a copy of the string with leading and trailing whitespace removed.

If chars is given and not None, remove characters in chars instead.
Type:      method_descriptor
print?
Docstring:
print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)

Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file:  a file-like object (stream); defaults to the current sys.stdout.
sep:   string inserted between values, default a space.
end:   string appended after the last value, default a newline.
flush: whether to forcibly flush the stream.
Type:      builtin_function_or_method
print('abc', 'def', 'xyz', sep=',')
abc,def,xyz