Reading a file Flashcards
1
Q
Opening a file
A
with open(example1, "r") as file1: FileContent = file1.read() print(FileContent) This is line 1 This is line 2 This is line 3
2
Q
Read first 4 characters
A
We don’t have to read the entire file, for example, we can read the first 4 characters by entering three as a parameter to the method .read():
# Read first four characters with open(example1, "r") as file1: print(file1.read(4)) This
3
Q
Readline()
A
We can also pass an argument to readline() to specify the number of charecters we want to read. However, unlike read(), readline() can only read one line at most.
4
Q
Read () vs. readline()
A
with open(example1, “r”) as file1:
print(file1.readline(20)) # does not read past the end of line
print(file1.read(20)) # Returns the next 20 chars
This is line 1
This is line 2
This