Table of Contents

Python Text File Creation and Data Writing

Example Description
Learn how to create and write data to text files in Python effortlessly. Explore a detailed tutorial on text file manipulation, covering file creation, data input, and user interaction. Master the art of persistent data storage using practical examples.

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:

  1. Open a file named “practice.txt” in write mode (“w+”) and assign the file object to fileobject.
  2. Enter a while loop that continues indefinitely until the user decides to stop.
  3. 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.
  4. Write the data to the file using the write method of the fileobject.
  5. Prompt the user whether they want to enter more data using the input function and store the answer in the variable ans.
  6. If the user’s input is ‘n’, exit the loop using the break statement.
  7. 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