codescracker


python

Python Program to Write to File



« Previous Program Next Program »


Write to File in Python

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.

Python Programming Code to Write to 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:

python write to file

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:

write to file in python

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:

python program write to file

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:

create a file and write some content inside the file

Same Program in Other Languages

You may also like to learn or practice the same program in other popular programming languages:


« Previous Program Next Program »




Tools
Calculator

Quick Links
Signup - Login - Give Online Test