Home » Python

How to write in an existing file in Python?

In this tutorial, we are going to learn how to write text in an existing file in python?
Submitted by IncludeHelp, on December 28, 2018

As we have discussed in previous post (Opening, closing a file/open(), close() functions in Python), that there are a set of file opening modes.

To write in an existing file - We have to open the file in append mode ("a"), if file does not exist, file will be created.

So, to write text in an existing file, first of all confirm that file exists or not? If the file does not exist, program will create a new file.

Example:

In this example, we will create a file first, write a text and then close the file. And then, we will open the file in append mode ("a").

# write content in an existing file
# first of all, we are creating a file 
# and writing some of the data

fo = open("file1.txt", "wt")
fo.write("Hello world.")
fo.close()

# now opening the file in append mode
fo = open("file1.txt","at")
fo.write("How are you?")
fo.close()

# reading and displaying conetnt of the file 
# opening the file in read only mode
fo = open("file1.txt","rt")
print("File's content...")
dummy = fo.read()
print(dummy)

fo.close()

Output

File's content...
Hello world.How are you? 





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.
Learn PCB Designing: PCB DESIGNING TUTORIAL







Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.