Python – text files

Links to Variables & Lists // Collections // Python editor // Conditions // Loops

Read from a text file

Create a textfile with the song of the previous chapter – or something else. Save your textfile as a plain textfile, using the extension .txt

source = open('song.txt', 'r', encoding = "utf-8")
text = source.read()
source.close()
print(text)

We use the open() function to create a file object source, which we can use to access the actual text content of the file. Make sure that you do not pass the 'w' parameter (“write”) to open(), instead of 'r' (“read”), since this would overwrite and thus erase the existing file.

After assigning the string returned by source.read() to the variable text, we print the text. Don’t forget to close the file again after you have opened or strange things could happen to your file! One little trick which is commonly used to avoid having to explicitly open and close your file is a with block (mind the indentation):

with open('song.txt', 'r', encoding = "utf-8") as source:
    text = source.read()
print(text)

This code block does exactly the same thing as the previous one but saves you some typing.

Write to a text file

Once you get familiar with the with block, it becomes quite evident.

with open('new_song.txt', 'w', encoding = "utf-8") as destination:    
    destination.write(text)

Note that we changed the reading mode ‘r’ into the writing mode ‘w’; we changed the name of the file object from source to destination; we used the function .write() instead of .read(). Once you have written your output to a new textfile, you can open the new file and read from it again…

By using ‘w’ you will overwrite and thus erase the existing content of your destination file. Use ‘a’ (from ‘append’) to add words to your existing file.