How to seek file pointer line by line in python - python

I am trying to seek the file pointer line by line, i found the following code
fo = open("temp.tmp", "r")
print "Name of the file: ", fo.name
"""Assuming file has following 5 lines:
This is 1st line
This is 2nd line
This is 3rd line
This is 4th line
This is 5th line
"""
line = fo.readline()
print "Read Line: %s" % (line)
# Again set the pointer to the beginning
fo.seek(3, 0)
line = fo.readline()
print "Read Line: %s" % (line)
fo.close()
but, it moves file pointer character by character, is there any way to seek the pointer line by line

Related

How to fetch the second line data from text file in Python

How to fetch the second line data from text file in Python.
I have a text file and in file there are some data in line by line_
Dog
Cat
Cow
How to fetch the second line which is “Cat” and store in a variable in python
var = # “Cat”
You should place the text file in the same directory with your Python code, which could be the following:
with open("animals.txt", "r") as f:
animals = [line.strip() for line in f]
second_line = animals[1]
Now, the variable "second_line" contains the data you want.
You can open a file, then read line by line while counting the line number as follows:
if __name__ == '__main__':
input_path = "data/animals.txt"
var = None
with open(input_path, "r") as fin:
n_lines = 0
for line in fin:
n_lines += 1
if 2 == n_lines:
var = line.strip()
break
print(var)
Result:
Cat
If the file is big, you may avoid reading all file and use readline to read one line twice:
with open ('file.txt') as file:
line = file.readline()
line = file.readline()
print(line)
...or check 'seek' method to start reading at specific character index.

List append and wrtite to an output

I am trying to append a string to my list and then write to an file
I used the following code:
temp=[line.split() for line in file]
for line in temp:
line=line.split()
line.append("string")
line=" ".join(line[0:-1]))
outputfile.write(line+'\n')
But when I checked the output file, instead of giving me string at the last field, it outputs some random number. Does anyone know what it happened?
Perhaps this is what you meant, it appends "string" to the end of each line.
outputfile = open( 'temp2.txt', 'w' )
temp=[ line.split() for line in open( 'temp1.txt' )]
for line in temp:
line.append("string")
line=" ".join(line)
outputfile.write(line+'\n')
Here is another way to do it:
outputfile = open( 'temp2.txt', 'w' )
temp=[ line.strip() for line in open( 'temp.txt' )]
for line in temp:
line = line + " string"
outputfile.write(line+'\n')
fname = "test.txt"
with open(fname,'r+') as f:
lines = f.readlines()
f.seek(0)
f.truncate()
for line in lines:
listString = line.split()
listString.append("your string \n")
newLine = " ".join(listString)
f.write(newLine)
test.txt
test
this is a file u read from
and u can add string at the end of each line
output test.txt
test your string
this is a file u read from your string
and u can add string at the end of each line your string
just make sure to add "\n" at the end of ur line for the new line

skip the first line after if condition

When I read a file line by line, I want to skip the first line that starts with ; after if condition[ word ] but my code gives the error below. How can I fix this error?
AttributeError: '_io.TextIOWrapper' object has no attribute 'next'
Code:
for line in open(inputfile, "r").readlines():
if "[ word ]" in line:
line = open(inputfile, "r").next()
You can use startswith to check how the line begins, and continue to move past that line
with open(inputfile, "r") as f:
for line in f:
if line.startswith(';'):
continue
...
You can do it like so:
with open(inputfile) as f:
for line in f:
if "[ word ]" in line:
line = f.readline() # 1
reassigns line to the next line than the one used by the if comparison.
you should just use continue and add variable to check is first line skiped:
with open(inputfile, "r") as f:
skip_first = False
for line in f:
if line.startswith(';') and skip_first:
skip_first = True
continue

Python: Script won't find word in text file

I am trying to find specific words from a text file, however my script doesn't seem to be able to match the word to what's written on a line in the text file, even though I know it matches. I've noticed there are spaces but since I am saying entry in line, shouldn't it work?
I have also tried:
if str(entry) in line:,
if str(entry) in str(line): and
if entry in str(line):
but none of them seem to work either
I can't see where I'm going wrong. Any help would be appreciated.
Here is my code
with open(address+'file_containing_data_I_want.txt') as f:
for entry in System_data:
print "Entry:"
print entry
for line in f:
print "Start of line"
print line
print"End of line"
if entry in line:
print "Found entry in line" #This never gets printed
Using the print statements (for just the first entry) I see:
Entry:
Manufacturer
Start of line
??
End of line
Start of line
End of line
Start of line
Manufacturer=manufacturer_data
End of line
Start of line
Model=model_data
End of line
Start of line
End of line
Start of line
End of line
The text file looks like this (Note:I can't change the text file as this is the way I will be receiving it, ' indicates a blank line):
'
'
Manufacturer=manufacturer_data
Model=model_data
'
'
'
UPDATE:
Changing my script to:
with open(address+'file_containing_data_I_want.txt') as f:
for line in f:
print "Start of line %s" % line
print"End of line"
for entry in System_data:
print "Entry: %s" % entry
if entry in line.strip():
print "Found entry in line"
Results in this being printed (Still no "Found entry in line"):
Entry: Manufacturer
Entry: Model
Start of line:
End of line
Entry: Manufacturer
Entry: Model
Start of line: Manufacturer=manufacturer_data
End of line
Entry: Manufacturer
Entry: Model
Start of line: Model=model_data
Entry: Manufacturer
Entry: Model
Start of line:
End of line
Entry: Manufacturer
Entry: Model
Start of line:
End of line
Changing my code to this:
for line in f:
print "Start of line: %s" % line.strip("\r\n")
print "End of line"
for entry in System_data:
print "Entry: %s" % entry.strip()
if entry.strip() in line.strip("\r\n"):
print "FOUND!!!!!!!!!!!!!"
Gives me this:
Start of line: ??
End of line
Entry: Manufacturer
Entry: Model
Start of line:
End of line
Entry: Manufacturer
Entry: Model
Start of line: Manufacturer=manufacturer_data
End of line
Entry: Manufacturer
Entry: Model
Start of line: Model=model_data
End of line
You read to the end of the file the after the first loop. Swap the loops instead, so each entry in System_data gets checked at each line of the file:
for line in f:
print "Start of line %s" % line
print "End of line"
for entry in System_data:
print "Entry: %s" % entry
if entry.strip() in line.strip("\r\n"):
print "Found entry in line" #This now gets printed
or you can correct this behavior in your current code by calling f.seek(0) before for line in f
You should strip all blanks/newlines from both the entry and lines in file. So, prefix everything with
entry = entry.strip()
and change the
if entry in line:
to
if entry in line.strip():
EDIT:
also, what Moses Koledoye says
Ok so it seems the issue was that the string was actually in hexadecimal form.
But it only appeared in hexadecimal form to me when I used print repr(line) it appeared like:
'\x00m\x00a\x00n\x00u\x00f\x00a\x00c\x00t\x00u\x00r\x00e\x00r\x00_\x00d\x00a\x0‌​0t\x00a\x00'
So I changed my code to the following:
with open(address+'file_containing_data_I_want.txt') as f:
for line in f:
for entry in System_data:
line=line.strip()
line = re.sub(r'[^\w=]', '', line)
if entry in line:
print "Found entry in line"
This script now enters the loop if entry in line: and prints "Found entry in line"

startswith() can't find '//' at the front of my string

I've got a pretty simple python script that reads in a file, and parses it line by line.
It doesn't seem to recognize the '//' at the start of my lines. If I change it to look for '#' at the start of my lines, it doesn't find those lines either. Am I just misunderstanding this?
line = fIn.readline()
while line:
print "line is", line
line = line.strip()
if line.startswith('//'):
print "winner"
line = fIn.readline()
The file I'm reading in looks like this:
// Feedback
"Feedback" = "Feedback";
// New strings
"File URL not reachable." = "File URL not reachable.";
And the debug line looks appropriate when it prints out:
line is // Feedback
line is "Feedback" = "Feedback";
line is
line is // New strings
line is "File URL not reachable." = "File URL not reachable.";
line is
Better version:
with open("abc") as f:
for line in f:
line=line.strip()
if line and line.startswith("//"):
print "line is",line
print "winner"
print next(f)
....:
output:
line is // Feedback
winner
"Feedback" = "Feedback";
line is // New strings
winner
"File URL not reachable." = "File URL not reachable.";
You are only reading one line of your text file. Other than you have the wrong indent on the last line, it seems to work. Try running your program after making sure line = fIn.readline() gets executed on each iteration (move it one block to the left).
Here is what I get after fixing that one line, is this the desired output?
line is // Feedback
winner
line is "Feedback" = "Feedback";
line is
line is // New strings
winner
line is "File URL not reachable." = "File URL not reachable.";
Edit: does this work for you?
for line in open("yourfile.txt").readlines():
print "line is", line
line = line.strip()
if line.startswith('//'):
print "winner"
try this
for line in fIn:
print "line is", line
line = line.strip()
if line[0:2]=='//':
print "winner"
line = fIn.readline()

Categories

Resources