Python Files
Files are named locations on disk to store related information. They are used to permanently store data in a non-volatile memory (e.g. hard disk).
Since Random Access Memory (RAM) is volatile (which loses its data when the computer is turned off), we use files for future use of the data by permanently storing them.
When we want to read from or write to a file, we need to open it first. When we are done, it needs to be closed so that the resources that are tied with the file are freed.
Hence, in Python, a file operation takes place in the following order:
Open a file
Read or write (perform operation)
Close the file
How to Open a Text File
To open a file, you need to use the built-in open function. The open function returns a file object that contains methods and attributes to perform various operations on the file.
Syntax
Primis Player Placeholder
file_object = open("filename", "mode")
Here,
filename: gives name of the file that the file object has opened.
mode: attribute of a file object tells you which mode a file was opened in.
Python has a built-in open() function to open a file. This function returns a file object, also called a handle, as it is used to read or modify the file accordingly.
>>> f = open("test.txt") # open file in current directory
>>> f = open("C:/Python38/README.txt") # specifying full path
We can specify the mode while opening a file. In mode, we specify whether we want to read r, write w or append a to the file. We can also specify if we want to open the file in text mode or binary mode.
The default is reading in text mode. In this mode, we get strings when reading from the file.
On the other hand, binary mode returns bytes and this is the mode to be used when dealing with non-text files like images or executable files.
Mode Description
r Opens a file for reading. (default)
w Opens a file for writing. Creates a new file if it does not exist or truncates the file if it exists.
x Opens a file for exclusive creation. If the file already exists, the operation fails.
a Opens a file for appending at the end of the file without truncating it. Creates a new file if it does not exist.
t Opens in text mode. (default)
b Opens in binary mode.
+ Opens 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("img.bmp",'r+b') # read and write in binary mode
How to Create a Text File
With Python you can create a .text files (Madanswer.txt) by using the code, we have demonstrated here
Step 1)
f= open("Madanswer.txt","w+")
We declared the variable f to open a file named Madanswer.txt. Open takes 2 arguments, the file that we want to open and a string that represents the kinds of permission or operation we want to do on the file
Here, we used "w" letter in our argument, which indicates write and will create a file if it does not exist in library
Plus sign indicates both read and write.
Step 2)
for i in range(10):
f.write("This is line %d\r\n" % (i+1))
We have a for loop that runs over a range of 10 numbers.
Using the write function to enter data into the file.
The output we want to iterate in the file is "this is line number", which we declare with write function and then percent d (displays integer)
So basically we are putting in the line number that we are writing, then putting it in a carriage return and a new line character
Step 3)
f.close()
This will close the instance of the file Madanswer.txt stored
Closing Files in Python
When we are done with performing operations on the file, we need to properly close the file.
Closing a file will free up the resources that were tied with the file. It is done using the close() method available in Python.
Python has a garbage collector to clean up unreferenced objects but we must not rely on it to close the file.
f = open("test.txt", encoding = 'utf-8')
# perform file operations
f.close()
Here is the result after code execution
Python FILE Tutorial: Create, Append, Read, Write
When you click on your text file in our case "Madanswer.txt" it will look something like this
Python FILE Tutorial: Create, Append, Read, Write
How to Append Data to a File
You can also append/add a new text to the already existing file or a new file.
Step 1)
f=open("Madanswer.txt", "a+")
Once again if you could see a plus sign in the code, it indicates that it will create a new file if it does not exist. But in our case we already have the file, so we are not required to create a new file.
Step 2)
for i in range(2):
f.write("Appended line %d\r\n" % (i+1))
This will write data into the file in append mode.
Python FILE Tutorial: Create, Append, Read, Write
You can see the output in "Madanswer.txt" file. The output of the code is that earlier file is appended with new data.
Python FILE Tutorial: Create, Append, Read, Write
How to Read a File
You can read a file in Python by calling .txt file in a "read mode"(r).
Step 1) Open the file in Read mode
f=open("Madanswer.txt", "r")
Step 2) We use the mode function in the code to check that the file is in open mode. If yes, we proceed ahead
if f.mode == 'r':
Step 3) Use f.read to read file data and store it in variable content
contents =f.read()
Step 4) print contents
We can read the text.txt file we wrote in the above section in the following way:
>>> 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
''
Here is the output
Python FILE Tutorial: Create, Append, Read, Write
How to Read a File line by line
You can also read your .txt file line by line if your data is too big to read. readlines() code will segregate your data in easy to read mode.
Python FILE Tutorial: Create, Append, Read, Write
When you run the code (f1=f.readlines()) for reading the file or document line by line, it will separate each line and present the file in a readable format. In our case the line is short and readable, the output will look similar to the read mode. But if there is a complex data file which is not readable, this piece of code could be useful.
File Modes in Python
Following are the various File Modes in Python:
Mode Description
'r' This is the default mode. It Opens file for reading.
'w' This Mode Opens file for writing.
If file does not exist, it creates a new file.
If file exists it truncates the file.
'x' Creates a new file. If file already exists, the operation fails.
'a' Open file in append mode.
If file does not exist, it creates a new file.
't' This is the default mode. It opens in text mode.
'b' This opens in binary mode.
'+' This will open a file for reading and writing (updating)
Here is the complete code
Python 2 Example
def main():
f= open("Madanswer.txt","w+")
#f=open("Madanswer.txt","a+")
for i in range(10):
f.write("This is line %d\r\n" % (i+1))
f.close()
#Open the file back and read the contents
#f=open("Madanswer.txt", "r")
# if f.mode == 'r':
# contents =f.read()
# print contents
#or, readlines reads the individual line into a list
#fl =f.readlines()
#for x in fl:
#print x
if __name__== "__main__":
main()
Python 3 Example
def main():
f= open("Madanswer.txt","w+")
#f=open("Madanswer.txt","a+")
for i in range(10):
f.write("This is line %d\r\n" % (i+1))
f.close()
#Open the file back and read the contents
#f=open("Madanswer.txt", "r")
#if f.mode == 'r':
# contents =f.read()
# print (contents)
#or, readlines reads the individual line into a list
#fl =f.readlines()
#for x in fl:
#print(x)
if __name__== "__main__":
main()