Writing Files We can open a file object using the method write() to save the text file to a list. To write the mode, argument must be set to write w. Let’s write a file Example2.txt with the line: “This is line A”
# Write line to file
with open('/resources/data/Example2.txt', 'w') as writefile:
writefile.write("This is line A")
We can read the file to see if it worked:
# Read file
with open('drive/app/xample2.txt', 'r') as testwritefile:
print(testwritefile.read())
We can write multiple lines:
# Write lines to file
with open('/resources/data/Example2.txt', 'w') as writefile:
writefile.write("This is line A\n")
writefile.write("This is line B\n")
The method .write() works similar to the method .readline(), except instead of reading a new line it writes a new line. The process is illustrated in the figure , the different colour coding of the grid represents a new line added to the file after each method call.
You can check the file to see if your results are correct
# Check whether write to file
with open('/resources/data/Example2.txt', 'r') as testwritefile:
print(testwritefile.read())
By setting the mode argument to append a you can append a new line as follows:
# Write a new line to text file
with open('/resources/data/Example2.txt', 'a') as testwritefile:
testwritefile.write("This is line C\n")
You can verify the file has changed by running the following cell:
# Verify if the new line is in the text file
with open('/resources/data/Example2.txt', 'r') as testwritefile:
print(testwritefile.read())
We write a list to a .txt file as follows:
# Sample list of text
Lines = ["This is line A\n", "This is line B\n", "This is line C\n"]
Lines
# Write the strings in the list to text file
with open('Example2.txt', 'w') as writefile:
for line in Lines:
print(line)
writefile.write(line)
We can verify the file is written by reading it and printing out the values:
# Verify if writing to file is successfully executed
with open('Example2.txt', 'r') as testwritefile:
print(testwritefile.read())
We can again append to the file by changing the second parameter to a. This adds the code:
# Append the line to the file
with open('Example2.txt', 'a') as testwritefile:
testwritefile.write("This is line D\n")
We can see the results of appending the file:
# Verify if the appending is successfully executed
with open('Example2.txt', 'r') as testwritefile:
print(testwritefile.read())
Copy a File Let's copy the file Example2.txt to the file Example3.txt:
# Copy file to another
with open('Example2.txt','r') as readfile:
with open('Example3.txt','w') as writefile:
for line in readfile:
writefile.write(line)
We can read the file to see if everything works:
# Verify if the copy is successfully executed
with open('Example3.txt','r') as testwritefile:
print(testwritefile.read())