Getting next line in a file - python

I am reading in a file and wonder if there's a way to read the next line in a for loop?
I am currently reading the file like this:
file = open(input,"r").read()
for line in file.splitlines():
line = doSomething()
So is there anyway I can retrieve the next line of the file in that for loop such that I can perform some operation in the doSomething() function?

Just loop over the open file:
infile = open(input,"r")
for line in infile:
line = doSomething(line, next(infile))
Because you now use the file as an iterator, you can call the next() function on the infile variable at any time to retrieve an extra line.
Two extra tips:
Don't call your variable file; it masks the built-in file type object in python. I named it infile instead.
You can use the open file as a context manager with the with statement. It'll close the file for you automatically when done:
with open(input,"r") as infile:
for line in infile:
line = doSomething(line, next(infile))

file = open(input,"r").read()
lines = file.read().splitlines()
for i in range(len(lines)):
line = lines[i]
next_line = lines[i+1]

I think that you mean that if you are in line n, you want to be able to access line n+1.
The simplest way to do that is to replace
for line in file.splitlines():
with
lines = file.readlines()
for i in xrange(len(lines)):
then you can get the current line with lines[i] and the next line with lines[i+1]
the more pythonic way is to use enumerate
lines = file.readlines()
for index, line in enumerate(lines):
now you have the current line in "line" like normal, but you also have the index if you want to find a different line relative to it.

Related

How to split a text file and store each line into a separate file? [duplicate]

This question already has answers here:
for each line in file write line to an individual file in python
(3 answers)
Closed 1 year ago.
I have a text file containing one string per line and I want to split each line of this text file and that each line should be stored as a separate text file.
Could you please help me out with this?
with open('filename.txt') as file:
lines = file.readlines()
# use an identifier from each line to ensure new file name is unique
line_num = 0
for line in lines:
try:
with open('line_{0}.txt'.format(line_num), 'w') as new_file:
new_file.write(line)
# increment the identifier
line_num+=1
except ():
print('Error occured')
This would work:
with open('filename') as file:
for line in file:
with open("change file name every time in this loop", "x") as newFile:
newFile.write(line)

not able to replace string in a file using replace method

Not able to replace the string in file
with open("dc_setup.tcl",'r+') as file:
for line in file:
if str0 in line:
line1=line
print(line1)
contents=file.read()
contents=contents.replace(line1,new_str)
file.seek(0)
file.truncate()
file.write(contents)
I expect the code to replace string in that file , but I'm getting empty file
This section:
file.seek(0)
file.truncate()
file.write(contents)
Is overwriting the entire file, not just your current line. Editing text files in place is generally pretty hard, so the usual approach is to write to a new file. You can copy the new file back over the old file once you've finished if you like.
with open("dc_setup.tcl") as infile, open("new_dc_setup.tcl", "w") as outfile:
for line in infile:
if old_str in line:
line = line.replace(old_str, new_str)
outfile.write(line)

How can I find certain words and print the line in python?

I am trying to print only the lines with the specific string I need.
I did this but I can't figure out what's wrong:
def find(text):
fisier = file('catastrofa.txt')
for line in fisier:
if (text in line):
print(line)
def main():
find("David")
main()
You open a file with open(..), you can then iterate over the file handler (iterating over a file handler will iterate over the file in a line-by-line fashion):
def find(text):
with open('catastrofa.txt') as fisier:
for line in fisier:
if (text in line):
print(line)
def main():
find("David")
main()
By default the mode in which you open the file is 'r', so you read the file (you can not write to it), and you read it as text (not binary).
Note that the path of the file is relative from the current directory (that can be the directory of the python file, but sometimes it is not).
You can open the file using open and use the readlines method for iterating line by line
def find(text):
fisier = open('catastrofa.txt')
for line in fisier.readlines():
if (text in line.strip()):
print(line)
fisier.close()
def main():
find("David")
main()
You can also use context manager that is with keyword that guarantees to close stream after you done, example already demonstrated by Willem Van Onsem
for line in fisier:
iterates over lines in file without removing line endings (usually the line return) so:
print(line)
will print the line and an empty line so it's better to write:
with open('catastrofa.txt') as fisier:
for line in fisier:
if text in line:
print(line, end='')
to avoid extra line returns.
Use open('catastrofa.txt') instead of file('catastrofa.txt')
like this:
def find(text):
fisier = open('catastrofa.txt','r')
for line in fisier:
if (text in line):
print(line)
def main():
find("David")
main()

How to skip reading first line from file when using fileinput method

I am doing this to read the file:
import fileinput
for line in fileinput.input('/home/manish/java.txt'):
if not fileinput.isfirstline():
... data = proces_line(line);
... output(data)
It is throwing error as proces_line is not defined.
Traceback (most recent call last):
File "<stdin>", line 3, in <module>
NameError: name 'proces_line' is not defined
I have to read the data line by line and store in list, each line being separate element of list.
You can skip the first line as follows:
import fileinput
def output(line):
print(line)
fi = fileinput.input('/home/manish/java.txt')
next(fi) # skip first line
for line in fi:
output(line)
This avoids you having to test for a first line each time in the for loop.
To store each of the lines into a list, you could do the following:
import fileinput
fi = fileinput.input('/home/manish/java.txt')
next(fi) # skip first line
output = list(fi)
fi.close()
print(output)
You can try with this:
fname = '/home/manish/java.txt'
with open(fname) as f:
content = f.readlines()
content is of type list. You can ignore content[0] and loop through with the rest to fetch the required data.
You are looking for the "readline ()" fuction. Pulls in the next line from the file and truncated the newline Python documentation for File Input
Usage
For each in openFile:
List += openFile.readline ()
In addition, you are trying to use a function that does not exist. As well as being miss spelled.

Python: How to select the first line of a text file, and after the second...? [duplicate]

This question already has answers here:
How to read a large file - line by line?
(11 answers)
Closed 8 years ago.
I'm in front of a problem in Python. Here is the thing: I have have a text file (textFile1.txt) with several lines
example:
This is the line 1
This is the line 2
This is the line 3
I can, in my python script, return all the content of my text file in writing:
def textFile1(self):
my_file = open("textFile1.txt")
my_file_contents = my_file.read()
return my_file_contents
With this function (read()), I return all the content of the file
Now, I would like to write in another text file that I call again with my python program:
The line 1 of my textFile1 is: This is the line 1
The line 2 of my textFile1 is: This is the line 2
The line 3 of my textFile1 is: This is the line 3
But the only thing I'm able to do is to write all the content each time (which is normal because I return all the content of the textFile1.txt) but I don't know how to select just the line 1 of the textFile1.txt, and after the line 2 and after the line 3...
So to summarize, my question is: how to select just ONE line of a text file, and after, to increment it (to print it in the terminal for example) ?
I think it's something like:
i=0
f = open("textFile.txt","r")
ligne = f.readline()
print ligne[i]
i=i+1
But in python, I don't know how to do.
Thank you
UPDATE:
Thanks for all your replies but till now, I'm still blocked.
By chance, is it possible to select one line from a text file in particular with this function:
for line in f:
print line.rstrip() # display all the lines but can I display just the line 1 or 2?
You want to loop over the lines of the file. Files provide a very simple interface to do that:
for line in f:
# Do whatever with each line.
Note that that the lines will include any trailing line break characters.
Also, it's generally best to open files in a with statement:
with open('textFile.txt', 'r') as f:
for line in f:
# Do whatever with each line.
This ensures that the file is closed when the with statement finishes, even in the presence of exceptions that might cause explicit close calls to be skipped or lingering references that would cause the file object's finalizer to be delayed.
def copy_contents(from_path, to_path):
from_file = open(from_path, 'r')
to_file = open(to_path, 'w')
for no, line in enumerate(from_file.readlines()):
to_file.write('This is line %u of my textFile: %s' % (no, line))
from_file.close()
to_file.close()
You can iterate over the file just line by line
with open('textFile1.txt') as f:
for line in f:
print line
# Write to the 2nd file textFile2.txt

Categories