How do I read a specific line on a text file? - python

Let me try to lay this out. I have a text file, each line of the text file is a different string. My trouble is if I want to grab line 3. When I try to use file.readline(3) or file.read(3) I will get the first 3 characters of the first line of the text file instead of all of line 3. I also tried file.readlines(3) but that just returned ['one\n'] which happens to yet again be the first line with [' \n'] around it. I am having more trouble with this that I already should be but I just gave up and need help. I am doing all of this through a discord bot if that helps, though that shouldn't be affecting this.

as what Barmar said use the file.readlines(). file.readlines makes a list of lines so use an index for the line you want to read. keep in mind that the first line is 0 not 1 so to store the third line of a text document in a variable would be line = file.readlines()[2].
edit: also if what copperfield said is your situation you can do:
def read_line_from_file(file_name, line_number):
with open(file_name, 'r') as fil:
for line_no, line in enumerate(fil):
if line_no == line_number:
file.close()
return line
else:
file.close()
raise ValueError('line %s does not exist in file %s' % (line_number, file_name))
line = read_line_from_file('file.txt', 2)
print(line)
if os.path.isfile('file.txt'):
os.remove('file.txt')
it's a more readable function so you can disassemble it to your liking

unfortunately you just can't go to a particular line in a file in a simple easy way, you need iterate over the file until you get to the desire line or know exactly where this line start withing the file and seek it and then read one line from it
for the first you can do:
def getline(filepath,n):
with open(filepath) as file:
for i,line in enumerate(file):
if i == n:
return line
return ""
Of course you can do file.readlines()[2] but that read ALL the file and put ALL its lines it into a list first, which can be a problem if the file is big
For the other option check this answer here

Related

How can i avoid new line at the end of the file?

i need to use
for line in doc.split('\n'):
and do some operation on each line but i got at the end of the file
empty line as i think it split a new line every time ! how can i avoid this problem ?
Please rephrase your question, since it is not very clear.
Anyway, if you are working with a text file you can just use:
with open("path_to_soruce_textfile", "r") as src, open("path_to_dest_textfile", "w") as dst:
for line in src.readlines(): # this gives you a list of lines with each line finishing with \n
processed_line = modidy(line)
dst.write(processed_line) # make sure \n is at the end of each line when you write
# the file is automatically closed

How do i check for a keyword in a specific line of a text file? python [duplicate]

I want to go to line 34 in a .txt file and read it. How would you do that in Python?
Use Python Standard Library's linecache module:
line = linecache.getline(thefilename, 33)
should do exactly what you want. You don't even need to open the file -- linecache does it all for you!
This code will open the file, read the line and print it.
# Open and read file into buffer
f = open(file,"r")
lines = f.readlines()
# If we need to read line 33, and assign it to some variable
x = lines[33]
print(x)
A solution that will not read more of the file than necessary is
from itertools import islice
line_number = 34
with open(filename) as f:
# Adjust index since Python/islice indexes from 0 and the first
# line of a file is line 1
line = next(islice(f, line_number - 1, line_number))
A very straightforward solution is
line_number = 34
with open(filename) as f:
f.readlines()[line_number - 1]
There's two ways:
Read the file, line by line, stop when you've gotten to the line you want
Use f.readlines() which will read the entire file into memory, and return it as a list of lines, then extract the 34th item from that list.
Solution 1
Benefit: You only keep, in memory, the specific line you want.
code:
for i in xrange(34):
line = f.readline();
# when you get here, line will be the 34th line, or None, if there wasn't
# enough lines in the file
Solution 2
Benefit: Much less code
Downside: Reads the entire file into memory
Problem: Will crash if less than 34 elements are present in the list, needs error handling
line = f.readlines()[33]
You could just read all the lines and index the line your after.
line = open('filename').readlines()[33]
for linenum,line in enumerate(open("file")):
if linenum+1==34: print line.rstrip()
I made a thread about this and didn't receive help so I took matter into my own hands.
Not any complicated code here.
import linecache
#Simply just importing the linecache function to read our line of choosing
number = int(input("Enter a number from 1-10 for a random quote "))
#Asks the user for which number they would like to read(not necessary)
lines = linecache.getline("Quotes.txt", number)
#Create a new variable in order to grab the specific line, the variable
#integer can be replaced by any integer of your choosing.
print(lines)
#This will print the line of your choosing.
If you are completing this in python make sure you have both files (.py) and (.txt) in the same location otherwise python will not be able to retrieve this, unless you specify the file location. EG.
linecache.getline("C:/Directory/Folder/Quotes.txt
This is used when the file is in another folder than the .py file you are using.
Hope this helps!
Option that always closes the file and doesn't load the whole file into memory
with open('file.txt') as f:
for i, line in enumerate(f):
if i+1 == 34: break
print(line.rstrip())

Python 2: How do I search for a string in a text file before returning the entire line from the text file that contains this string?

Use case:
The user enters an ID code.
A stored file contains information about people, one line per person, including their ID codes.
I need to find this user's line in the file and append that to another text file.
with open("file.txt") as file:
for line in file:
if id_code in line:
yield line
Now what? How do I go from yielding the line to getting it in another file? Also, if the id code isn't in the file at all, can I ask them to try again?
Without the actual txt file, it's hard to say if this will work perfectly, but it's the right general idea.
with open("file.txt", "r") as f, open("otherfile.txt", "a") as g:
for line in file.readlines():
lineparts = line.split()
if id_code in lineparts:
g.write(line)

Get line number python from opened file

I wrote this little Python 2.7 prototype script to try and read specified lines (in this example lines 3,4,5) from a formatted input file. I am going to be later parsing data from this and operating on the input to construct other files.
from sys import argv
def comparator (term, inputlist):
for i in inputlist:
if (term==i):
return True
print "fail"
return False
readthese = [3,4,5]
for filename in argv[1:]:
with open(filename) as file:
for line in file:
linenum=#some kind of way to get line number from file
if comparator(linenum, readthese):
print(line)
I fixed all the errors I had found with the script but currently I don't see anyway to get a line number from file. It's a bit different than pulling the line number from a file object since file is a class not an object if I'm not mistakened. Is there someway I can pull the the line number for my input file?
I think a lot of my confusion probably stems from what I did with my with statement so if someone could also explain what exactly I have done with that line that would be great.
You could just enumerate the file object since enumerate works with anything iterable...
for line_number, line in enumerate(file):
if comparator(line_number, line):
print line
Note, this indexes starting at 0 -- If you want the first line to be 1, just tell enumerate that's where you want to start:
for line_number, line in enumerate(file, 1):
...
Note, I'd recommend not using the name file -- On python2.x, file is a type so you're effectively shadowing a builtin (albeit a rarely used one...).
You could also use the list structure's index itself like so:
with open('a_file.txt','r') as f:
lines = f.readlines()
readthese = [3,4,5]
for lineno in readthese:
print(lines[1+lineno])
Since the list of lines already implicitly contains the line numbers based on index+1
If the file is too large to hold in memory you could also use:
readthese = [3,4,5]
f = open('a_file.txt','r')
for lineno in readthese:
print(f.readline(lineno+1))
f.close()

Go to a specific line in Python?

I want to go to line 34 in a .txt file and read it. How would you do that in Python?
Use Python Standard Library's linecache module:
line = linecache.getline(thefilename, 33)
should do exactly what you want. You don't even need to open the file -- linecache does it all for you!
This code will open the file, read the line and print it.
# Open and read file into buffer
f = open(file,"r")
lines = f.readlines()
# If we need to read line 33, and assign it to some variable
x = lines[33]
print(x)
A solution that will not read more of the file than necessary is
from itertools import islice
line_number = 34
with open(filename) as f:
# Adjust index since Python/islice indexes from 0 and the first
# line of a file is line 1
line = next(islice(f, line_number - 1, line_number))
A very straightforward solution is
line_number = 34
with open(filename) as f:
f.readlines()[line_number - 1]
There's two ways:
Read the file, line by line, stop when you've gotten to the line you want
Use f.readlines() which will read the entire file into memory, and return it as a list of lines, then extract the 34th item from that list.
Solution 1
Benefit: You only keep, in memory, the specific line you want.
code:
for i in xrange(34):
line = f.readline();
# when you get here, line will be the 34th line, or None, if there wasn't
# enough lines in the file
Solution 2
Benefit: Much less code
Downside: Reads the entire file into memory
Problem: Will crash if less than 34 elements are present in the list, needs error handling
line = f.readlines()[33]
You could just read all the lines and index the line your after.
line = open('filename').readlines()[33]
for linenum,line in enumerate(open("file")):
if linenum+1==34: print line.rstrip()
I made a thread about this and didn't receive help so I took matter into my own hands.
Not any complicated code here.
import linecache
#Simply just importing the linecache function to read our line of choosing
number = int(input("Enter a number from 1-10 for a random quote "))
#Asks the user for which number they would like to read(not necessary)
lines = linecache.getline("Quotes.txt", number)
#Create a new variable in order to grab the specific line, the variable
#integer can be replaced by any integer of your choosing.
print(lines)
#This will print the line of your choosing.
If you are completing this in python make sure you have both files (.py) and (.txt) in the same location otherwise python will not be able to retrieve this, unless you specify the file location. EG.
linecache.getline("C:/Directory/Folder/Quotes.txt
This is used when the file is in another folder than the .py file you are using.
Hope this helps!
Option that always closes the file and doesn't load the whole file into memory
with open('file.txt') as f:
for i, line in enumerate(f):
if i+1 == 34: break
print(line.rstrip())

Categories

Resources