Links to Variables & Lists // Collections // Python editor // Conditions // Loops // Functions // Working with libraries // Exercises
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.
Now we can apply code to our imported text:
with open('song.txt', 'r', encoding = "utf-8") as source:
text = source.read()
words = text.split()
for word in words:
print(word)
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.
We continue with the variable ‘words’ from above, that contains all the text of our source text file:
# initiate counter as a way to define the position of the element in the list
position = 0
# initiate empty list
new_words = []
# loop through all elements of my list
for element in words:
# print element and its position in the list
print(element, position)
# create variable that contains element and position (int turned into string str())
new_word = element + str(position)
# add variable to my empty list
new_words.append(new_word)
# actualize counter
position += 1
# convert string to list using breaks
delimiter = "\n "
new_words_string = delimiter.join(new_words)
# write result into a new textfile
with open('new_words.txt', 'w', encoding = "utf-8") as destination:
destination.write(new_words_string)