how to write files in python | appending files in python

So far we have seen how to read text files in python with different modes.

Check our previous posts to know more

Lets see few examples related to read files in python here

Example1

myfile = open(r'E:\poem. txt", "r")
str - myfile.read()
size = len(str)
print("Size of the given file poem.txt is")
print(size, "bytes")

Output

The size of the given file poem.txt is

387 bytes

Example2

myfile-open(r'E:\poem.txt', "r")
S = myfile.readlines
linecount = len(s)
print("The Number of lines in the poem.txt is", linecount)
myfile.close()

Output

The number of lines in the poem. txt is 18

Writing into Text files

Subsequent to working with file-reading functions, let us talk about the writing functions for data files available in Python.

Like reading functions, the writing functions also manage open files, i.e. the files that are opened and linked via a file object or filehandle.

Method1

Write()

Syntax

<filehandle>.write(str1)

Explanation

the write function writes string str1 to file referenced by <filehandle>

Method2

Writelines()

Syntax

<filehandle>.writelines(L)

Explanation

writes all strings in list L as lines to file referenced by <filehandles>.

Appending a file

When we open a file in “w” or write mode, Python overwrites an existing file or creates a

non-existing file.

This means, for an existent file with the same name, the earlier data will get lost.

However, we want to write into the file while retaining the old data,

then we should open the file in “a” or append mode. A file opened in append mode retains its previous data while allowing you to add newer data into it.

we can also add a plus symbol (+) with file read mode to help reading as well as writing.

In conclusion, we can write files by several methods

  1. In an existing file, while geting its content
    1. if the file has been opened in append mode (“a”) to retain the old content,
    2. if the file has been open in ‘r’ or ‘at’ modes to facilitate reading as well as writing,
  2. to create a new file or to write on an existing file after overwriting its old
    1. if the file has been opened in write-only mode (“w”),
    2. if the file has been open in ‘w+’ mode to facilitate writing as well as reading.
  3. we have to make sure to use close( ) function on file-object after we have finished writing as sometimes, the content remains in memory buffer and to force-write the content on file and closing the link of file-handle from file, close( ) is used.

we can show the contents of a file created through write( ). 

It is clear from the file-contents that write( ) does not add any extra character like the newline character(’\n’) after every write operation. Thus to group the contents you are writing in file, line-wise, make sure to write newline characters on our own.

We will be happy to hear your thoughts

Leave a reply

Edusera
Logo
Open chat
1
Scan the code
Hello!👋
Can we help you?