There are three steps to reading or writing files in Python.
You can open a file in python by ‘open’ function. open() returns a file object, and is most commonly used with two arguments: open(filename, mode).
There are four different methods (modes) for opening a file:
"r" - Read - Default value. Opens a file for reading, error if the file does not exist.
"a" - Append - Opens a file for appending, creates the file if it does not exist.
"w" - Write - Opens a file for writing, creates the file if it does not exist.
"x" - Create - Creates the specified file, returns an error if the file exists.
f = open('workfile.txt', 'w')
You should always close a file after doing stuffs. For this you can use close() function.
It is good practice to use the with keyword when dealing with file objects. The advantage is that the file is properly closed after its suite finishes, even if an exception is raised at some point. Using with is also much shorter than writing equivalent try-finally blocks.
with open("workfile.txt") as f: for line in f: print(line) # After printing the lines the file will be closed.
If mode field is empty, it will open the file in ‘r’ read mode.
To read a file’s contents, call f.read(size), which reads some quantity of data and returns it as a string (in text mode) or bytes object (in binary mode). Size is an optional numeric argument. When size is omitted or negative, the entire contents of the file will be read and returned.
#“workfile.txt” contains following lines #This is first line #This is second line #This is third line with open("workfile.txt", "r") as f: data = f.read() print(data)
This is first line This is second line This is third line
f.readline() reads a single line from the file.
with open("workfile.txt", "r") as f: data = f.readline() print(data)
This is first line
The readlines() method to get a list of string values from the file, one string for each line of text.
with open("workfile.txt", "r") as f: data = f.readlines() print(data)
['This is first line\n', 'This is second line\n', 'This is third line\n']
Python allows you to write content to a file. You can’t write to a file you’ve opened in read mode, though. Instead, you need to open it in “write plaintext” mode or “append plaintext” mode, or write mode and append mode for short. Write mode will overwrite the existing file and start from scratch. Pass 'w' as the second argument to open() to open the file in write mode. Append mode, on the other hand, will append text to the end of the existing file. If the filename passed to open() does not exist, both write and append mode will create a new, blank file.
f.write(string) writes the contents of string to the file, returning the number of characters written f = open('workfile.txt', 'w') f.write('This is a test\n') f.write('Hi User!\n') f.write('Welcome to Python Easy!\n') f.close() f = open('workfile.txt') content = f.read() f.close() print(content)
This is a test Hi User! Welcome to Python Easy!