Python
In this tutorial we will learn to work with files in Python.
We use the open function to create a new file in Python.
open
The open function takes two arguments. The first argument is the name of the file to be created. The second argument is the mode and it is set to x.
x
In the following Python program we are creating a file by the name helloworld.txt.
helloworld.txt
# create a new file fObj = open("helloworld.txt", "x") fObj.close()
In the above code we are creating a file using the open() function.
open()
It is a good practice to flush any unwritten data and close the file using the close() function.
close()
If the file already exists then open("filename", "x") will return an error.
open("filename", "x")
If we run the above code again we will get the following error as the file helloworld.txt exists.
Traceback (most recent call last): File "/Users/yusufshakeel/PycharmProjects/HelloWorld/files/file.py", line 2, in <module> fObj = open("helloworld.txt", "x") FileExistsError: [Errno 17] File exists: 'helloworld.txt'
We can also use the absolute file path to create files.
In the following Python program we are creating hello.txt file using absolute path.
hello.txt
# create a new file fObj = open("/Users/yusufshakeel/PycharmProjects/HelloWorld/files/hello.txt", "w") fObj.close()
To check if a given file exists we have to use the os module.
os
In the following Python program we are importing the os module and then checking the existence of a given file.
# import module import os # check if os.path.exists("helloworld.txt"): print("File exists") else: print("File does not exists")
To write data in a file we use the open function in write w mode. Then we use the write function to write the data.
w
write
If the file does not exists then open("filename", "w") will create the file.
open("filename", "w")
In the following Python program we are opening the helloworld.txt file in write mode and writing "Hello World" string in the file.
"Hello World"
# open file fObj = open("helloworld.txt", "w") # write data fObj.write("Hello World\n") fObj.close()
If we open the helloworld.txt we will get to see the "Hello World" line in the file.
In the above code we are using new line \n escape sequence.
\n
To append data to a file we use the open function and set the mode to a append mode.
a
If the file does not exists then open("filename", "a") will create the file.
open("filename", "a")
In the following Python program we are opening the helloworld.txt file in append mode and appending string "Some more text." to the file.
"Some more text."
# open file fObj = open("helloworld.txt", "a") # append data fObj.write("Some more text.\n") fObj.close()
To read the content of a file we use the open function with r read mode.
r
If the file does not exists then open("filename", "r") will return error.
open("filename", "r")
In the following Python program we are reading the content of the helloworld.txt file that we have created earlier.
# open file fObj = open("helloworld.txt", "r") # read data data = fObj.read() # output print(data) fObj.close()
The above code will give use a similar output.
Hello World Some more text.
Note! Your output may vary based on what you have written in the file.
read
By default, the read function will read all the content of the file.
If we want to read limited number of characters then we can pass numbers to the function.
In the following Python program we are reading only 5 characters of the helloworld.txt file.
# open file fObj = open("helloworld.txt", "r") # read data data = fObj.read(5) # output print(data) fObj.close()
The above code will give us a similar output.
Hello
readline
We use the readline function to read file one line at a time.
In the following Python program we are printing the first two lines of the helloworld.txt file using the readline function.
# open file fObj = open("helloworld.txt", "r") # read 1st line data = fObj.readline() # output print(data) # read 2nd line data = fObj.readline() # output print(data) fObj.close()
Each time we use readline function it reads a line and then moves to the next line.
To read file line by line we can take help of for loop.
In the following Python program we are reading the content of the helloworld.txt file line by line using for loop.
# open file fObj = open("helloworld.txt", "r") for line in fObj: print(line) fObj.close()
To delete a file we use the remove function from the os module.
remove
In the following Python program we are removing the hello.txt file that we created earlier.
# import module import os # check and remove if os.path.exists("hello.txt"): print("File exists... Removing it...") os.remove("hello.txt") else: print("File does not exists")