For storing information permanently we need files. We shall be learning data file handling in python in this section and work with data file.
Data file handling in Python(Writing to file)
In simple word we create a simple program to enter any string(s) in python and that string store in text file permanently.
Data file handling in Python (Reading from file)
In this section python file extract data from text file and display in python output.
Both writing and reading to file or from file is called data file handling in python.
For both cases we need text file ( Notepad in case of windows or any other text file creator like vim editor , notepadqq , notepad++, Gedit etc. for Linux , TextEdit in mac). In my post/video I run and demonstrate python code in windows.
Either you have to write data from python to notepad or read data from notepad to python , you need a file. Two options are there
- Create a file in notepad and save.
- Python itself create a file (through coding) and write operation perform to write data to that file.
First option is quite easy as you can done yourself after learning option number two. Take a new program and starts writing code given below.
f=open(“abc.txt”,”w”)
f is file object also called file-handle. We declare f as file object (you can take any name). Then open function (as named suggest) open the file “abc.txt” if already exist (in our system) otherwise creates non existing file and open it in memory (RAM). Remember if file is already exist earlier data gets lost. For example suppose file abc.txt is already exists and having some data in it but after running this line blank file is there all data is lost. If you want to write into the file while retaining the old data, you should open the file in “a” append mode. For example
f=open(“abc.txt”,”a”)
After that “w” is write mode means file open in memory and you perform write operation to file.
write () filehandle.write(str1) :- write string str1 to file referenced by filehandle eg abc.txt in this case. “Welcome to all” is now content of your file abc.txt. Open abc.txt and see. Now little questions by many students where abc.txt is created ???. Look at the above example of python module example1.py, it was saved in c:\NEHA\example1.py so by default “abc.txt” also created and opened from this location. You can change the location like this..
f=open(“e:\\RAHUL\\abc.txt”,”w”)
here I mentioned complete path from where I want to opened file . You can try but remember
- first create folder named RAHUL in e: drive and
- use \\ double slash instead of single slash \ (as single slash is reserved for escape sequences like \n \t etc.)
if you want to use single slash then prefix r in front of , it makes it raw string that means there is no special meaning attached to any character. Remember following statement gives error..
f=open(“e:\RAHUL\abc.txt”,”w”) but
by prefixing r like f=open(r”e:\RAHUL\abc.txt”,”w”) it works fine.
So two ways to give path in filenames correctly are :
- double the slashes like f=open(“e:\\RAHUL\\abc.txt”,”w”)
- Give raw string by prefixing the file path with n r like f=open(r”e:\RAHUL\abc.txt”,”w”)
See the content of file abc.txt below.
For more understadning you can watch this video on writing to file in Python.
At last f.close() is must to close the file from memory.
See the another code
f=open(“abc.txt”,”w”)
s=input(“Enter String=”)
f.write(s)
f.close()
It will accept string from user at runtime and write that string to file abc.txt.
You can write multiple lines to file by using loops see the example
f=open(“abc.txt”,”w”)
n=int(input(“How many lines=”))
for i in range(n):
s=input(“Enter string=”)
f.write(s +”\n”)
f.close()
here f.write(s +”\n”) because write() does not add new line character on its own. So “\n” newline character written after every string. You can try this code without “\n” and see the content of abc.txt it will like this
NahaMansiKasish
Suppose I was entered 3 strings “Neha” , “Mansi”, “Kasish” .
writelines() : write () function only accept strings but writelines() write all strings in the list L as lines to file referenced by <filehandle>
f=open(“abc.txt”,”w”)
n=int(input(“How many lines=”))
L=[] #empty list
for i in range(n):
s=input(“Enter string=”)
L.append(s+”\n”)
f.writelines(L)
f.close()
after running above python code
Content of “abc.txt” after running above code is