python writing to a text file code example
Example 1: python write to file
file = open(“testfile.txt”,”w”)
file.write(“Hello World”)
file.write(“This is our new text file”)
file.write(“and this is another line.”)
file.write(“Why? Because we can.”)
file.close()
Example 2: python write to file
path = "guide/README.txt"
with open(path, "w") as fil:
fil.write("This is the README. It is reccomended that you read it.")
fil.close()
'''
List of methods:
w* - replace everything with needed text
r^ - read the file
a* - adds to file
x - creates file
* Creates file if the file at that path does not exist
^ Throws error if file does not exist
'''
Example 3: reading and writing data in a text file with python
file1 = open("MyFile.txt","a")
file2 = open(r"D:\Text\MyFile2.txt","w+")
file1 = open("MyFile.txt","a")
file1.close()
file1 = open("myfile.txt","w")
L = ["This is Delhi \n","This is Paris \n","This is London \n"]
file1.write("Hello \n")
file1.writelines(L)
file1.close()
file1 = open("myfile.txt","r+")
print "Output of Read function is "
print file1.read()
print
file1.seek(0)
print "Output of Readline function is "
print file1.readline()
print
file1.seek(0)
print "Output of Read(9) function is "
print file1.read(9)
print
file1.seek(0)
print "Output of Readline(9) function is "
print file1.readline(9)
file1.seek(0)
print "Output of Readlines function is "
print file1.readlines()
print
file1.close()
file1 = open("myfile.txt","w")
L = ["This is Delhi \n","This is Paris \n","This is London \n"]
file1.close()
file1 = open("myfile.txt","a")
file1.write("Today \n")
file1.close()
file1 = open("myfile.txt","r")
print "Output of Readlines after appending"
print file1.readlines()
print
file1.close()
file1 = open("myfile.txt","w")
file1.write("Tomorrow \n")
file1.close()
file1 = open("myfile.txt","r")
print "Output of Readlines after writing"
print file1.readlines()
print
file1.close()
Output of Readlines after appending
['This is Delhi \n', 'This is Paris \n', 'This is London \n', 'Today \n']
Output of Readlines after writing
['Tomorrow \n']
Example 4: how write to file in python
f = open("demofile2.txt", "a")
f.write("Now the file has more content!")
f.close()
f = open("demofile2.txt", "r")
print(f.read())