Handling Text file in Python (Writing Data in Text file)
Storing data in text file is one of the important work people use to do in any language. If you will go for C++ and Java, you have to write lots of code for doing and making connection of stream explicitly and have to import many additional libraries to do so.
But here in case of python you no need to worry about all these. You have to write just few line of code to write data into text file. Here is the sample code.
fout = open("StuTextFile.txt","a+") name = input("Enter your name : ") addr = input("Enter address : ") school = input("Enter school : ") str = name+"\t"+addr+"\t"+school fout.write(str) fout.close()
Code description –
In first line of code a file “StuTextFile.txt” will get open in append mode so that data entered will get saved again and again without overwriting it in to file. As you know default file mode is r+ to read, w+ for write and a+ to append.
Second, third and fourth line is just to get input from user (name, addr, school). Fifth line is creating a string with tab space. Sixth line is the important line to call write() function on the file object created (fout). Last line is to close the file object. It means file object’s connection with file will be disconnected.