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:
![](https://i0.wp.com/tekcookie.com/wp-content/uploads/2020/04/1Line.jpg?resize=364%2C176&ssl=1)
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:
![](https://i0.wp.com/tekcookie.com/wp-content/uploads/2020/04/2Lines.jpg?resize=361%2C177&ssl=1)
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:
![](https://i0.wp.com/tekcookie.com/wp-content/uploads/2020/04/append.jpg?resize=372%2C182&ssl=1)
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:
![](https://i0.wp.com/tekcookie.com/wp-content/uploads/2020/04/listtotext.jpg?resize=371%2C178&ssl=1)
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:
![](https://i0.wp.com/tekcookie.com/wp-content/uploads/2020/04/range.jpg?resize=365%2C295&ssl=1)
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:
![](https://i0.wp.com/tekcookie.com/wp-content/uploads/2020/04/range-2.jpg?w=1080&ssl=1)
>
![](https://i0.wp.com/tekcookie.com/wp-content/uploads/2020/04/dest_demo-1.jpg?w=1080&ssl=1)
Thank you for reading this article. Hope this is helpful to you.
Recent Comments