The first type of file we are going to read from is a simple text file with multiple lines of text. To do that, let's first create a text file with the following lines:
in order to guys,
you need to fall
but what if, in order to fall
you need to guys
Save this as myfile.txt to the desktop. Next, open the interpreter and type the code below:
f = open('myfile.txt', 'r')
firstline = f.readline()
secondline = f.readline()
print(firstline)
print(secondline)
f.close()
The first line in the code opens the file. Before reading a file, we have to open it. The open() function does exactly that and requires two parameters:
1. The path to the file. If fileOperation.py and myfile.txt are stored in two different folders, you would have to replace 'myfile.txt' with its actual path.
2. The mode. This specifies how the file will be used. The commonly used modes are:
1. 'r', for reading
2. 'w', for writing. If the specified file does not exist, it will be created. If it does exist, any existing data on the file will be erased.
3. 'a', for appending. If the specified file does not exist, it will be created. If it does exist, any data written to it will automatically add to the end
4. 'r+', for reading and writing.
After opening the file, the next statement firstline = f.readline() reads the first line in the file and assigns it to firstline.
Each time the readline() function is called, it reads a new line from the file. In our program, readline() was used twice. Hence, the first two lines will be read.
Output
in order to guys,
you need to fall
Notice how there is a line break after each line. This is because readline() adds '\n' at the end of each line. To get rid of it, we can do print(firstline, end = ''). This removes '\n'. After reading and printing the first two lines, f.close() closes the file. Files should always be closed after the program finishes reading to free up any system resources.
No comments:
Post a Comment