896+ Capstone Project is Available: Whatsapp: +91-7011258995, Email: sharecodepoint@gmail.com

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'

file.write('content')

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 !!')
else:
    print('Thank you for using our services')

files = open(file_name, 'w')
files.write(aboutself)

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 : 

file 

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

Video Tutorial :

Sharecodepoint

Sharecodepoint is the junction where every essential thing is shared for college students in the well-defined packets of codes. We are focused on providing you the best material package like Question papers, MCQ'S, and one NIGHT STUDY MATERIAL. facebook twitter youtube instagram

Post a Comment

Previous Post Next Post

Contact Form