Python File Handling: Create, Append and Write : Program to create file & writing something in the file

In this program, we will learn how to create a file & how to write something in the file by taking the input from the user in python. User will enter some data and if user wants to save the file then will press 'yes' or if not  then press 'no'.

Python File Handing : File handling is an important part of any application. Python has several functions for reading, creating, deleting, and updating files. In this program ,we are using open() file handing function. Add a parameter to the open() function: 

"a"  - Append - Append to the end of the file.
syntax : file = open(file_name,  'a')

"w" - Write -  Overwrite any existing content.
syntax : file = open(file_name, 'w')

"x"  - Create - Create a file, returns an error if the file does not exist.
syntax : file = open(file_name, 'x')

a, w and x are the methods of open() function.

If you are writing using 'w' method ,the old content  will be overwritten by the new content. If you don't want to overwrite the old content then use 'a' method (Append).

Syntax : 
file = open(file_name, 'w') # 'a' or 'x' or 'w'


Python Code : ('w' Method Example)
print('welcome to sharecodepoint videos')
print('Write somthing about yourself')
aboutself = str(input())
choose = str(input('You want to save this file (yes/no)? '))
if choose == 'yes' or choose == 'Yes':
    print('Enter your file name : ')
    file_name = str(input())
    print('Your file is successfully saved !!')
    print('Thank you for using our services')

files = open(file_name, 'w')

Output :
welcome to sharecodepoint videos 

Write somthing about yourself 

Hello dude !! Welcome to sharecodepoint videos 

You want to save this file (yes/no)? yes 

Enter your file name : 


Your file is successfully saved !! 
Process finished with exit code 0

Video Tutorial :

Post a Comment

* Please Don't Spam Here. All the Comments are Reviewed by Admin.
Post a Comment (0)

buttons=(Accept !) days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !
To Top