While in python does not print all the rows - python

Dear I want display the three rows contained in txt file but I don't know why the following code does not works.
The code is
f=open("dati.txt","r")
riga=f.readline()
while riga!="":
print(f.readline())
riga=f.readline()
f.close()

because you are reading two lines in a loop. The readline moves the cursor one down each time you call it. So what happens there with the second call of readline() you actually skip it(in the print log)
Also checking for end of file should not be done on empty string, because you may hit an empty line before the end of the file. Try this instead:
with open('somefile') as openfileobject:
for line in openfileobject:
do_something()
and or/check this thread(where I copied the snippet from): What is the perfect counterpart in Python for "while not EOF"

The reason why your program is not printing all the rows in the file, but rather only every even numbered row, is because you use f.readline() multiple times in the while statement.
f=open("dati.txt","r")
riga=f.readline() # This line means that the variable "riga" contains the first line in your file
while riga!="":
print(f.readline()) # here you do f.readline() again, which means that what you are printing is the second line
riga=f.readline() # This line reads in the third line into the "riga" variable.
f.close()
What I think you are looking for, is to print the contents of the riga variable instead, like this
while riga != "":
print(riga)
riga = f.readline()
I should also mention that tstoev's answer also has a good approach at printing each line in a file. It does solve the same problem, but it does not point out why your code doesn't work.

Your code reads three lines and prints only one:
f=open("dati.txt","r")
riga=f.readline() # Reads a line into riga
while riga!="":
print(f.readline()) # Reads a line and prints it
riga=f.readline() # Reads a line into riga
f.close()
So the problem seems that you read lines into riga, but never print riga.

Related

Index Error When Deleting Lines From A txt File

lines = file.readlines()
del lines[68]
This is the code im using to delete the lines, I have already opened the file it works with lots of other stuff. When I run this code it pops up with an index error when Im deleting lines in the middle of the txt file. I ve tried many versions of deleting lines in the txt file but none of them work. Any ideas?
In short
You can add f.seek(0) before f.readlines(), and try your code again.
Long explain
I tried your code and it seems working normally when deleting single element in lines.
Did you use f.readlines() multiple times? In that case, the second time this method will return empty list because the first call already move the cursor to end of file.
To read the file again, you have to use this method f.seek(0) to move the cursor back to the begin of file before calling f.readlines()
How about testing if the txt file has 69 lines at all ?
def delete_line(path, number)
f = opne(path, "r")
lines = f.readlines()
f.close()
if len(lines) - 1 < number:
print("The file %s has not a line number %d" % (path, number))
else:
del lines[number]
return lines
Use it like this:
lines = delete_line("path/to/file/you/want/to/delete/a/line/from.txt", 68)
If your file was long enough, you will have the file minus the specified line saved in lines, else a warning will be printed and the value of lines will be the unmodified file.

Using line.replace twice in the same line

I am trying to use line.replace such that I can replace two separate variables in the same line before moving onto the next line.
lets say the text file "file.txt' is:
(1.00)
(2.00)
(3.00)
I would like to replace the ( and ) with and empty space for each line. Here is what I have.
file=open('file.txt', 'r')
file_1=open('file_1.txt', 'w')
for line in file:
x=line.replace('(', "")
file_1.writelines(x)
file_2=open('file_1.txt', 'r')
file_3=open('file_2.txt', 'w')
for line in file_2:
y=line.replace(')', "")
file_3.writelines(y)
Is there a way to make this more efficient?
Thank you for your help,
Kyle
You just need to call the replace function a second time after you do it the first time:
for line in file:
x=line.replace('(', "")
x=x.replace(')', "")
file_1.writelines(x)
Or, you could even call the replace function twice on the same line:
for line in file:
x=line.replace('(', "").replace(')', "")
file_1.writelines(x)
You can make this much simpler. As others have said, you can call replace twice, because it does return a string, so you could do...
for line in file:
x=line.replace('(', "").replace(')', "")
file_1.writelines(x)
You don't actually need the x either, so you can combine them into one line. The works because the replace function keeps returning a string.
for line in file:
file_1.writelines(line.replace('(', "").replace(')', ""))
And now that it's a one line for loop, we can make this even simpler into a list comprehension. Making the entire program
file=open('file.txt', 'r')
file_1=open('file_1.txt', 'w')
[file_1.writelines(line.replace('(', "").replace(')', "")) for line in file]
Don't hesitate to ask questions.

how to save changes after modifying content in file using Python

I want to insert a line into file "original.txt" (the file contains about 200 lines). the line neds to be inserted two lines after a string is found in one of the existing lines. This is my code, I am using a couple of print options that show me that the line is being added to the list, in the spot I need, but the file "original.txt" is not being edited
with open("original.txt", "r+") as file:
lines = file.readlines() # makes file into a list of lines
print(lines) #test
for number, item in enumerate(lines):
if testStr in item:
i = number +2
print(i) #test
lines.insert(i, newLine)
print(lines) #test
break
file.close()
I am turning the lines in the text into a list, then I enumerate the lines as I look for the string, assigning the value of the line to i and adding 2 so that the new line is inserted two lines after, the print() fiction shows the line was added in the correct spot, but the text "original.txt" is not modified
You seem to misunderstand what your code is doing. Lets go line by line
with open("original.txt", "r+") as file: # open a file for reading
lines = file.readlines() # read the contents into a list of lines
print(lines) # print the whole file
for number, item in enumerate(lines): # iterate over lines
if testStr in item:
i = number +2
print(i) #test
lines.insert(i, newLine) # insert lines into the list
print(lines) #test
break # get out of the look
file.close() # not needed, with statement takes care of closing
You are not modifying the file. You read the file into a list of strings and modify the list. To modify the actual file you need to open it for writing and write the list back into it. Something like this at the end of the code might work
with open("modified.txt", "w") as f:
for line in lines: f.write(line)
You never modified the original text. Your codes reads the lines into local memory, one at a time. When you identify your trigger, you count two lines, and then insert the undefined value newLine into your local copy. At no point in your code did you modify the original file.
One way is to close the file and then rewrite it from your final value of lines. Do not modify the file while you're reading it -- it's good that you read it all in and then start processing.
Another way is to write to a new file as you go, then use a system command to replace the original file with your new version.

How to prevent the reading of a text file from stopping at an empty line?

My problem is that my input file contains empty lines (this is a must), but when it reaches an empty line, the: for i, line in enumerate(file): stops reading the file. How do I prevent this.?
The reading of the file is like this, because I need to do something with every one but the last line of a file, than something else with the last line. (This is also a must.)
Here is what I'm trying to do:
with open(sys.argv[1]) as file:
i = 0
for i, line in enumerate(file):
# Do for all but last line
if i < linecount-1:
print "Not last line"
i += 1
# Do for last line
if i == linecount-1:
print "Last line"
It works fine on files without empty lines.
You do not need to declare or increment i in your code. enumerate does that for you. Incrementing additionally as you do probably triggers your conditionals accidentally; it has nothing to do with empty lines.
The mistake in your implementation is explained in the other answer, but to achieve what I think you want to do, it might be better to process as follows, then you don't need to know the length of the file in advance:
import sys
def process_regular_line(line):
print 'regular line', line
def process_last_line(line):
print 'last line:', line
with open(sys.argv[1]) as file:
last_line = file.readline()
while True:
this_line = file.readline()
if not this_line:
process_last_line(last_line)
break
process_regular_line(last_line)
last_line = this_line
For example, on the test file with 5 lines:
a line
another line
a line after a blank line
The last ever line
You get:
regular line: a line
regular line: another line
regular line:
regular line: a line after a blank line
last line: The last ever line

Python: Write to next empty line

I'm trying to write the output of something that is being done over three big iterations and each time I'm opening and closing the outfile. Counters get reset and things like this after the iterations and I'm a massive newb and would struggle to work around this with the shoddy code I've written. So even if it's slower I'd like change the way it is being output.
Currently for the output it's just rewriting over the first line so I have only the output of the last run of the program. (tau, output are variables given values in the iterations above in the code)
with open(fileName + '.autocorrelate', "w") as outfile:
outfile.writelines('{0} {1}{2}'.format(tau, output, '\n'))
I was wondering if there are any quick ways to get python to check for the first empty line when it opens a file and write the new line there?
Open with "a" instead of "w" will write at the end of the file. That's the way to not overwrite.
If you open your file in append mode : "a" instead of "w", you will be able to write a new line at the end of your file.
You do do something like that to keep a reference (line number) to every empty line in a file
# Get file contents
fd = open(file)
contents = fd.readlines()
fd.close()
empty_line = []
i = 0
# find empty line
for line in contents:
if line == "":
empty_line.append(i)
i+=1

Categories

Resources