Working with files in Python

Being able to work with files is important in Python. How to open a text file and read its content? How to write or append some content to a file?

Read content from a file with Python

fileOpened = open("C:\...\textfile.txt", "r")
# r default, w, a, r+, add b for binary mode
readAll = fileOpened.read()
fileOpened.close()

 

Or alternatively for good practice, using the with statement will automatically close the file after the indentation

with open("C:\...\textfile.txt", "r") as fileOpened:
    readAll = fileOpened.read()
print(fileOpened.closed)
#True 
#=> the file is closed
print( fileOpened.read(10))
# since the file is already closed we have an error
#ValueError: I/O operation on closed file.

 A cursor is positioned to read the file.

with open("C:\...\textfile.txt", "r") as fileOpened:
    print( fileOpened.read(15))
    print( fileOpened.read(25))
    # The reading cursor is advancing
    fileOpened.seek(offset=-10, from_what=2) #0 current position, 1 beginning of file, 2 end of file
    print(fileOpened.tell())
    print(fileOpened.readline()) #This reads one full line

 

 It is possible to treat the file content as a list object:

with open("C:\...\textfile.txt", "r") as fileOpened:
    for line in fileOpened:
        print(line)
   
# Alternatively
with open("C:\...\textfile.txt", "r") as fileOpened:
    AllLines = list(fileOpened)

 

Write content in a file with Python 

f = open("C:\...\textfile.txt ", "a")
f.write("hello world")
#f.writelines("hello world")

Save and load JSON objects in a file

import json
json.dumps(TheList)
#write the content of the object
f = open("C:\File.json", "r+")
json.dumps(TheList, f)

LoadedList = json.load(f)

Matthieu Liatard
Remember this!
Remember this
Play!
Take a quizz on this subject
Close

Hello :)
At Question-Player, we want to share more knowledge and help you never forget anything ever. And for free.

To show us your support, you can create an account:

Login / Create an account
Rate this article :
1
2
3
4
5

Up next

Related posts