Computer Science · Ch 2 — File Handling in Python
Creating a file and writing data
Creating a file and writing data
To create a file in Python, you use the open() method. This method takes two essential arguments: the filename and the mode in which you want to open it. The mode determines what you can do with the file — read, write, or append.
When you open a file in write mode (w), Python prepares the file for writing. If a file with that name already exists, opening it in write mode erases all its existing content and creates a fresh, empty file with the same name. If no file with that name exists, Python simply creates a new empty file for you.
When you open a file in append mode (a), Python also prepares the file for writing, but it does not erase existing content. Instead, any new data you write gets added to the end of the file, after whatever was already there. If the file does not exist, append mode also creates a new empty file.
A common mistake is to open an existing file in write mode (w) thinking you are just adding to it. This will destroy all previous data in that file. Use append mode (a) if you want to preserve existing content.
Program 2-3: To create a text file and write data in it
# program to create a text file and add data
fileobject=open("practice.txt","w+")
while True:
data= input("Enter data to save in the text file: ")
fileobject.write(data)
ans=input("Do you wish to enter more data?(y/n): ")
if ans=='n': break
fileobject.close()
Output of Program 2-3:
>>>
RESTART: Path_to_file\Program2-3.py
Enter data to save in the text file: I am interested to learn about Computer Science
Do you wish to enter more data?(y/n): y
Enter data to save in the text file: Python is easy to learn
Do you wish to enter more data?(y/n): n
>>>
``` …