Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append a text to file in Python [duplicate]

Tags:

python

io

  1. How to check that the file exists?
  2. How to append a text to the file?

I know how to create the file, but in this case, it overwrites all data:

import io

with open('text.txt', 'w', encoding='utf-8') as file:
    file.write('text!')

In *nix I can do something like:

#!/bin/sh

if [ -f text.txt ]
    #If the file exists - append text
    then echo 'text' >> text.txt; 

    #If the file doesn't exist - create it
    else echo 'text' > text.txt;  
fi;
like image 702
tomas Avatar asked Feb 15 '12 16:02

tomas


People also ask

How do you duplicate a text file in Python?

The shutil. copy() method in Python is used to copy the content of the source file to destination file or directory.

Does Python write overwrite?

Writing to a file requires a few decisions - the name of the file in which to store data and the access mode of the file. Available are two modes, writing to a new file (and overwriting any existing data) and appending data at the end of a file that already exists.

How do you append a text?

Select the Insert tab, and from the Text group, select Object . Select Text from File from the drop-down list. Select the file and select Insert .


1 Answers

Use mode a instead of w to append to the file:

with open('text.txt', 'a', encoding='utf-8') as file:
    file.write('Spam and eggs!')
like image 118
Sven Marnach Avatar answered Oct 03 '22 15:10

Sven Marnach