Reading and Writing Files
For a more in-depth look at file and directory path manipulation, see the File and directory Paths page.
The file Reading/Writing process
To read/write to a file in Python, you will want to use the with statement, which will close the file for you after you are done, managing the available resources for you.
Opening and reading files
The open function opens a file and return a corresponding file object.
# Read file using 'with' statement: automatically closes file when done
with open('/home/labex/project/hi.txt') as hello_file:
hello_content = hello_file.read() # Read entire file content
hello_content
'Hello World!'
Quiz
Sign in to answer this quiz and track your learning progress
What is the main advantage of using the
with statement when opening files?A. The file is automatically closed when done, even if an error occurs
B. Files open faster
C. Files can be opened in read and write mode simultaneously
D. Files are automatically compressed
Alternatively, you can use the readlines() method to get a list of string values from the file, one string for each line of text:
# readlines() method: returns list of strings, one per line
with open('sonnet29.txt') as sonnet_file:
sonnet_file.readlines() # Returns list with each line as a string
['When, in disgrace with fortune and men's eyes,\n',
' I all alone beweep my outcast state,\n',
"And trouble deaf heaven with my bootless cries,\n",
"And look upon myself and curse my fate,']
You can also iterate through the file line by line:
# Iterate through file line by line (memory efficient for large files)
with open('sonnet29.txt') as sonnet_file:
for line in sonnet_file: # File object is iterable
print(line, end='') # Print without extra newline
When, in disgrace with fortune and men's eyes,
I all alone beweep my outcast state,
And trouble deaf heaven with my bootless cries,
And look upon myself and curse my fate,
Writing to files
# Write to file: 'w' mode overwrites existing file
with open('bacon.txt', 'w') as bacon_file: # 'w' = write mode
bacon_file.write('Hello world!\n') # Returns number of characters written
13
# Append to file: 'a' mode appends to existing file
with open('bacon.txt', 'a') as bacon_file: # 'a' = append mode
bacon_file.write('Bacon is not a vegetable.')
25
with open('bacon.txt') as bacon_file:
content = bacon_file.read()
print(content)
Hello world!
Bacon is not a vegetable.
Quiz
Sign in to answer this quiz and track your learning progress
What is the difference between opening a file with mode
'w' and mode 'a'?A.
'w' is for reading, 'a' is for writingB.
'w' overwrites the file, 'a' appends to the fileC.
'w' is for Windows, 'a' is for AppleD. There is no difference