Introduction:
Text file manipulation is a fundamental skill for Python programmers. In this tutorial, we provide a comprehensive guide on creating text files and writing data to them. Through a step-by-step example, you’ll learn how to interact with users to input data and populate a text file, enhancing your Python programming capabilities.
Code:
# 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()
Logic:
- Open a file named “practice.txt” in write mode (“w+”) and assign the file object to fileobject.
- Enter a while loop that continues indefinitely until the user decides to stop.
- Prompt the user to enter data they wish to save in the text file using the input() function, and store the input in the variable data.
- Write the data to the file using the write method of the fileobject.
- Prompt the user whether they want to enter more data using the input function and store the answer in the variable ans.
- If the user’s input is ‘n’, exit the loop using the break statement.
- Close the file using the close() method to save changes and release resources.
Output:
>> Enter data to save in the text file: python
>>Do you wish to enter more data?(y/n): y
>>Enter data to save in the text file: i love
>>Do you wish to enter more data?(y/n): n