My Coding > Programming language > Python > Working with files in Python

Working with files in Python

Working with files in Python

Open and read file

Files can be open for reading, writing and appending in binary and text mode. Pythong give a lot of different ways to work with files.# r – read (default, can be omitted), w-write, a-append, r+ - read write

Read whole file in one go

It is possible to read all file in one go


f = open("test.txt","r", encoding="utf-8") # open file for reading in text mode utf-8 codding
x = f.read()      # read all file into x
f.close()         # close file
print(x)          # print content of this file
print(repr(x))    # print contend of this file with showing all special symbols
y=x.splitlines()  # y – list of lines without ‘end of line’ symbols

If you will give parameters for read(N) – it will read next N-characters. You need to be careful with this parameters. It will read N-characters in selected coding. By default it will read N-bytes. If the file encoding will be stated, it will read N- characters in this encoding.

Read file by lines

If file is pretty big, it is better to read it line by line and process accordingly


f = open("test.txt","r", encoding="utf-8") # open file for reading
for line in f:
    line = line.rstrip()                   # remove enf of line
    print(line)                            # use our line from file
f.close()

Open and immediately close file

To avoid any problems with file, it is better to close it immediately after use. Python give very simple tool for closing file immediately after reading


with open("test.txt","r", encoding="utf-8") as f:
    for line in f:
        line = line.rstrip()
        print( line )
# at the end of block WITH, file will be closed automatically

Work with few files together

Python allow to work in WITH block with few files together


with open("test.txt","r", encoding="utf-8") as f, open("test_copy.txt", "w") as w:
    for line in f:
        w.write(line)
# at the end of block WITH, file “test.txt” will be copied to “test_copy.txt”


Published: 2021-09-29 07:15:43
Updated: 2021-09-29 08:19:44

Last 10 artitles


9 popular artitles

© 2020 MyCoding.uk -My blog about coding and further learning. This blog was writen with pure Perl and front-end output was performed with TemplateToolkit.