To write some content to a file in python, you have to ask from user to enter the name of file along with their extension like filename.txt. Then open that file if exist, or create a file with that name and again ask from the user to enter some line of sentences to put those sentences into the file as the content of the file.
Following python program ask from the user to enter the file name to open/create a file and again ask to enter three lines of sentence to put those sentences in the file as the content of the file.
Before start going to python code to learn how to write some content to a file, let's first see the current directory's folder. In this folder you will see which files already exist to create a new file inside the same directory. Here is the folder's snapshot before file create:
Here is the python program, used to create a new file and writes some content entered by the user:
# Python Program - Write to File while True: print("Enter 'x' for exit.") filename = input("Enter file name to create and write content: ") if filename == 'x': break else: c = open(filename, "w") print("\nThe file,",filename,"created successfully!") print("Enter 3 sentences to write on the file: ") sent1 = input() sent2 = input() sent3 = input() c.write(sent1) c.write("\n") c.write(sent2) c.write("\n") c.write(sent3) c.close() print("Content successfully placed inside the file.!!\n")
Here is the sample run of the above python program:
Now you will see a new file is created inside the same folder as shown here. This is the snapshot of the folder after running the above python program:
After opening the text file which you have created with the above python program, you will see all the entered content successfully placed inside this file as shown in the following snapshot:
You may also like to learn or practice the same program in other popular programming languages: