This article will describe how to write content to a text file using python
Write one line to text file
Set the argument to ‘w’ to write to a file. If the file does not exists, new file is created
file = open("demo.txt", 'w')
file.write("this is first line")
file.close()
Output:
Write two lines to text file
file = open("demo.txt", 'w')
file.write("this is first line")
file.write("\n")
file.write("this is second line")
file.close()
Output:
Append data to a text file
Set the argument to ‘a’ to append to a file. If the file does not exists, new file is created
"r" - Default mode, open the file in read mode "x" - Create a file, returns an error if the file exist "a" - Append to the file, will create a file if the specified file does not exist "w" - Write to the file, will create a file if the specified file does not exist
file = open("demo.txt", 'a')
file.write("\n")
file.write("this is third line")
file.write("\n")
file.write("this is fourth line")
file.close()
Output:
Write a list of string to text file
string = ["first line", "\n", "second line", "\n", "third line"]
file = open("demo.txt", 'w')
file.writelines(string)
file.close()
Note: file.write() function will write string to text file and file.writelines() will write a list of strings to text file
Output:
Write from 1 to 10 to text file
file = open("demo.txt", 'w')
for num in range(1,10):
file.write(str(num) + "\n")
file.close()
Output:
Copy content from one file to other
file = open("demo.txt")
with open("dest_demo.txt",'w') as dest_demo:
dest_demo.writelines(file.readlines())
file.close()
Copy content from demo.txt to dest_demo.txt
Output:
>
Thank you for reading this article. Hope this is helpful to you.
Recent Comments