Working With Files Using Python;
Here is how to read, write, append, and delete files using python.
Hey there!👋
In this article, you are going to learn how to handle Text files using Python.
First I want you to open your Jupyter Notebook, if you don’t have a Jupyter Notebook no problem, you can open Google Colab or VSCode.
Now create a folder and put a sample Text file.
Now just code along.
The Python file in which you are coding should be in the same folder along with those sample files so that we will be able to easily access them and do some read, write, and other operations.
import os
os.getcwd()
# My Output: 'C:\\Users\\urabb\\My Work'To know your current working directory, you just need to import the os module and call the getcwd() method, the cwd in getcwd() method stands for current working directory.
Working With .txt Files:
Reading:
As both my Python file and the sample text file are in the same directory, I can simple open the sample text file using it’s name in my case the name is “sample.txt”.
Here is how you open the text file.
# Opening File
f = open("sample.txt")After opening the file and storing it in a variable f, now we can read it using the read() method.
txt = f.read()
print(txt)
""" Output:
This is a text file
I am learning Data Science """Now imagine it like this, In the first step I created a variable f to store the file (sample.txt), and in the second step I created a variable txt to store the content of the file. Now whatever the content is in the sample.txt file will be printed in the output.
In Python after performing an operation you need to close the file, you can’t perform two operations at the same time, you need to close the file before performing the second operation.
To close the file we use close().
f.close()Now the file is closed.
Get Abbas Ali’s stories in your inbox
Join Medium for free to get updates from this writer.
There is another method called readlines() which will return a list with each line in the text file as elements. To understand this better see the below code and output.
f = open("sample")
txt = f.readlines()
print(txt)
f.close()
""" Output: ['This is a text file\n', 'I am learning Data Science\n']"""Hope you got it now.
If you don’t like to close the file after each operation there is another way to achieve the same result and here is how you do it.
with open('sample.txt') as file:
print(file.read())
""" Output:
This is a text file
I am learning Data Science """Using the above code will open the file and stores its content in a variable file. Now you don’t have to use the close() method.
To perform readlines() you can do the same.
with open('sample') as file:
print(file.readlines())
""" Output: ['This is a text file\n', 'I am learning Data Science\n']"""Writing:
Now you know how to read text files, let’s learn how to write files.
# Writing File
fw = open('sample2.txt', 'w') # Write Mode
fw.write("I am awesome!")
fw.close()By default, open() method will use the read operation, but if you want to write you need to specify a ‘w’ like in the above code which represents “Write Mode”.
The above code will create a new file named sample2.txt and using the the write() method we can add content to the file in the above case, I have add the content “I am awesome!” and that’s true.
You can check your directory there will be a new text file named sample2.txt. You can also read the file using the read() method we previously learned.
Append:
With write() method we can create a file and write our own content in it as you saw previously. Using the append() method we can add more content to an existing file.
# Append File
fw = open('sample.txt', 'a') # Append Mode
fw.write("\nThis line is written by me using append!!!")
fw.close()
""" Output:
This is a text file
I am learning Data Science
This line is written by me using append!!!"""As you can see in the code our sample.txt file a new line is added.
Deleting:
It’s is always hard to create something and easy to destroy it. You can delete a file using the below code.
# Deleting File
os.remove('sample2.txt')If you don’t know whether the file you want to remove exist in the directory or not in that case you can use the below code.
if os.path.exists('sample'):
os.remove('sample')
else:
print("File does not exist")Hope you learned something today.
Please do leave a comment if you don’t know what to comment just leave a emoji.
Bye bye… See ya!








