Add encoding: file = open(filename, encoding="utf8")
Here is what the above code is Doing:
1. Opening the file in read mode.
2. Reading the contents of the file into a variable called “contents”.
3. Closing the file.
The contents of the file are now stored in the variable “contents”.
You can print the contents of the file like this:
print(contents)
You can also access individual lines in the file like this:
print(contents[0])
print(contents[1])
print(contents[2])
…etc.
You can also store the contents of the file in a list like this:
lines = contents.split(“\n”)
This will split the contents of the file at every newline character and store each line in a separate element in the list “lines”.
You can access individual lines in the list like this:
print(lines[0])
print(lines[1])
print(lines[2])
…etc.
Task:
Write a program that reads the contents of a text file and prints it to the screen.
The file to read is this one:
https://raw.githubusercontent.com/mlepaine/zero-to-mastery-coding-challenges/master/week-02/input.txt
Your program should:
1. Open the file in read mode.
2. Read the contents of the file into a variable.
3. Print the contents of the file to the screen.
4. Close the file.
Bonus:
1. Store the contents of the file in a list.
2. Print the contents of the list, one element per line.
Hint:
You can use the “split” method to split the contents of a string into a list of strings.