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.
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
.
In the following Python program we are creating a file by the name 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.
It is a good practice to flush any unwritten data and close the file using the close()
function.
If the file already exists then open("filename", "x")
will return an error.
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.
# 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.
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.
If the file does not exists then open("filename", "w")
will create the file.
In the following Python program we are opening the helloworld.txt
file in write mode and writing "Hello World"
string in the file.
# 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.
To append data to a file we use the open
function and set the mode to a
append mode.
If the file does not exists then open("filename", "a")
will create the file.
In the following Python program we are opening the helloworld.txt
file in append mode and appending string "Some more text."
to the file.
# 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.
If the file does not exists then open("filename", "r")
will return error.
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
functionBy 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
functionWe 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.
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")
ADVERTISEMENT