Writing to a text file : Text file « File « Python Tutorial






print "Creating a text file with the write() method."
text_file = open("write_it.txt", "w")
text_file.write("Line 1\n")
text_file.write("line 2\n")
text_file.write("line 3\n")
text_file.close()

print "\nReading the newly created file."
text_file = open("write_it.txt", "r")
print text_file.read()
text_file.close()

print "\nCreating a text file with the writelines() method."
text_file = open("write_it.txt", "w")
lines = ["Line 1\n",
         "line 2\n",
         "line 3\n"]
text_file.writelines(lines)
text_file.close()

print "\nReading the newly created file."
text_file = open("write_it.txt", "r")
print text_file.read()
text_file.close()

raw_input("\n\nPress the enter key to exit.")








12.3.Text file
12.3.1.First Python Programs
12.3.2.File Read and Display
12.3.3.Demonstrates reading from a text file
12.3.4.Reads a plain text file
12.3.5.Writing to a text file
12.3.6.Open a file and save text to it
12.3.7.Storing and parsing Python objects in files
12.3.8.print to a file