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 that 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 print("Enter 'x' for exit."); filename = input("Enter file name to create and write content: "); if filename == 'x': exit(); 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("\nContent successfully placed inside the file.!!");
Here is the sample run of the above python program:
Above is the initial output, now let's enter the filename say mynewfile.txt and press enter button to create a new file as shown in the sample run given below:
Now you will see a new file is created inside the same folder named python as shown here.This is the snapshot of the folder after running the above python program. This folder contains a new file named mynewfile.txt with empty contents:
Now let's enter the content, that is three line of sentences, that is first enter This is my first sentence. and press enter, again enter This is my second sentence. and press enter, and again enter This is my third sentence. and again press enter to put all these contents inside the file named mynewfile.txt as shown in below sample run:
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 named mynewfile.txt as shown in the following snapshot:
You may also like to learn or practice the same program in other popular programming languages: