Reputation: 11
I want to open specific lines from an ordinary text file in python. is there anyway to do this? and how?
Upvotes: 0
Views: 95
Reputation: 8521
First lets see how to open a file to write:
f = open(‘filename.txt’, ‘w’)
Now we have opened a file named filename, in write mode. Write mode is indicated using ‘w’. If a file of that particular name is not present then a new file would be created.
It has created an object of that particular file and we can do all our operations on that particular object. Now we have created an object for writing. The command to write is:
text = “Hello Python”
f.write(text) ## or f.write(“Hello Python”)
After doing all our required operations, we need to close the file. The command to close the file is as follows:
f.close()
This will save the file and close it. Now lets see how to read a file.
f = open(‘filename.txt’, ‘r’)
Same like write, but only the mode is changed to ‘r’. Now we have opened a file named filename, in read mode. Read mode is indicated using ‘r’. If a file of that particular name is not present then an error will be raised
Traceback (most recent call last):
File "", line 1, in
IOError: [Errno 2] No such file or directory: 'filename.txt'
If the file is present, then it would create an object of that particular file and we can do all our operations on that particular object. Now we have created an object for reading. The command to read is:
text = f.read()
print text
All the contents of the file object is now read and stored in the variable text. Text holds the entire contents of the file.
After doing all our required operations, we need to close the file. The command to close the file is as follows:
f.close()
In the above examples we have opened the file separately and close it separately, there is a better way to do it using with function. The modified code will be
with open(‘filename.txt’, ‘r’) as f:
text = f.read()
print text
When it comes out of the with block it will automatically close the file.
Upvotes: 0
Reputation: 2916
presuming that you want the line m
and the name file is file.txt
with open('file.txt') as f:
line = f.read().splitlines()[m]
print(line)
line
is the line that you want.
Upvotes: 2
Reputation: 3341
If the lines are selected by line numbers which follow a consistent pattern, use
itertools.islice
.
E.g. To select every second line from line 3 up to but not including line 10:
import itertools
with open('my_file.txt') as f:
for line in itertools.islice(f, 3, 10, 2):
print(line)
Upvotes: 1