Tag Archives: #reading

Reading and writing files in Python

Reading and writting files is very important so that we can manipulate data and keep it even after our program has ceased to live. In order to understand both task I made a Python3 program that reads a .txt file and copies its content to other one. 

Mi program is available in Github. You can also find the text files that I used to test the program.

The program is the following:

C = open("Original.txt","r")

V = open("Test.txt","w")

 

for line in C:

    print(line,end="")

    V.write(line)

C.close()

V.close()

What the program does is very simple, first we open/create our files. This is done usign the function open(), where our first argument should be the name of the file, and the second one is the mode in which we are going to open it. In this case “r” stands for reading, and “w” for writing.

I found in the Python3 Documentation that the best way to read a files lines is by usign the for loop of the lines in the file. This helps us to do it in a very efficient and clean way.

In this case every line is printed in the console that you may compare what has been writen in the new file and what has been read. 

Then we write each line that we read in the new file. 

And as for any file writting and reading operation we close our files. 

For the file reading and writing the official documentation has the other functions that you can perform, like usign f.seek() to perform searches , or how to acces a certain part of the file.

This is my of my