Python Loop Only Parses First Five Lines of Text File - python

I'm attempting to read and print a .txt file line-by-line in Python using the readline function. The below code is intended to print out the entire text file line-by-line, but as of right now, it only prints out the first five lines of the text file.
filename = input("Enter the name and extension of the file you want to open.")
file = open(filename, "r")
fileline = file.readline()
for line in fileline:
fileline = fileline.rstrip("\n")
print(fileline)
fileline = file.readline()
file.close()
I expect the code to print out the entire file line by line, but it currently only prints out the first five lines. What is the bug in the code?

This line:
for line in fileline:
is looping through the characters of fileline, which contains the first line of the file. So if the first line has 5 characters, this loop will execute 5 times.
Then inside the loop, you print the line and then read the next line into the fileline variable. That has no effect on the loop, which is still iterating over the characters in the first line.
To make the program deliberately print the first 5 lines, you can do:
for i in range(5):
fileline = file.readline()
if (fileline == ''): #end of file reached
break
print(fileline.rtrim('\n'))
Or you can iterate over file, which automatically reads lines, and use a separate counter variable
i = 0
for line in file:
print(line.rtrim('\n'))
i += 1
if i == 5:
break

Related

Moving text file to integer list [duplicate]

I have a .txt file that I created with multiple lines.
When I run a for loop, with a count accumulator, it skips lines.
It skips the top line, and starts with the second, prints the fourth, the sixth, etc.
What is it I'm missing?
def main():
# Open file line_numbers.txt
data_file = open('line_numbers.txt', 'r')
# initialize accumulatior
count = 1
# Read all lines in data_file
for line in data_file:
# Get the data from the file
line = data_file.readline()
# Display data retrieved
print(count, ": ", line)
# add to count sequence
count += 1
Try removing the "line=data_file.readline()" altogether? I suspect the "for line in data_file:" is also a readline operation.
You for loop is iterating over the data_file and your readline() is competing with it. Erase the line = data_file.readline() line of your code for this result:
# Read all lines in data_file
count = 1
for line in data_file:
# Display data retrieved
print(count, ": ", line)
# add to count sequence
count += 1
for line in data_file already gets the text of each line for you - the subsequent call to readline then gets the following line. In other words, removing the call to readline will do what you want. At the same time, you don't need to keep track of an accumulator variable yourself - python has a built-in way of doing this using enumerate - in other words:
data_file = open('line_numbers.txt', 'r')
for count, line in enumerate(data_file):
...

How to format a text file such that it removes blank files and trailing space

I have test.txt that looks like the screenshot
PS: There are trailing spaces in the second line, so it is < space > line 2
in result we have to get:
line 1
line 2
line 3
This is what I have so far
with open("test", 'r+') as fd:
lines = fd.readlines()
fd.seek(0)
fd.writelines(line for line in lines if line.strip())
fd.truncate()
But it is not handling cases when the line starts with space (in the example, line 2) , How do I modify my code? I want to us Python
Test.txt file:
first line
second line
third line
Python Code:
#// Imports
import os
#// Global Var's
fileName:str = "test.txt"
#// Logic
def FileCorection(file:str):
try:
#// Read original file
with open(file, "r") as r:
#// Write a temporary file
with open(f"temp_{file}", "w") as w:
# Get line from original file
line = r.readline()
# While we still have lines
while line:
# Make a temporary line with out spaces at the end and also at the front of the line (in case they are)
tempLine:str = line.strip()
#// Check if the line is empty
if tempLine == "":
Line:tuple = (False, "Empty line...")
#// If not then get the line
else:
Line:tuple = (True, tempLine)
#// Print/Show Line if is True... in this case you care set witch line to pre writed in a new file
if Line[0] == True:
print(Line[1])
w.write(f"{Line[1]}\n")
line = r.readline()
finally:
# Make shore the files are closed
# By default they shood but just to make shore
r.close()
w.close()
# Now repalce the temp file with the original one
# By replaceing we delete the original one and we rename the temporary one with the same name
os.remove(file)
os.rename(f"temp_{file}", file)
if __name__ == "__main__":
FileCorection(fileName)
# Show when is done
print(">> DONE!")
Console out:
first line
second line
third line
>> DONE!
Process finished with exit code 0
P.S.: The code was updated/optimized!
I would suggest formatting the input(screenshot of the text file would do). Assuming your input looks like this you can use strip when text begins with a space.
#Code
with open(r"demo.txt","r") as f:
data = f.read()
data_list = [s.strip() for s in data.split("\n") if len(s)>0]
print("\n".join(data_list))

Printing all sets in list python

fob=open('c:/Users/username/Desktop/CE151 Python/ass2/grid.txt','r')
text_file = open("grid.txt","r")
for item in fob:
tuple(item.split(';')[0:])
print(item[0:])
I have loaded a text file and I am trying put each line into a list.When I can for the first line it prints only 1 line. Even when i call for all lines it still outputs 1 line. How do I print a line i request for.
grid.txt contains:
paghzkctudptjdphsztprhttl
sbsnakjwqbouftmgnjqbtlinu
tsewohvobdsduqjiffkyylodo
oukwwefroyamapmlrrpvdolop
cqkfxtlksjvtmtrsbycmqrrri
kfervlqidqaxaoanfqjlmcpjh
yoyywrbpfcjlfbcbbcoecspwl
twbxetyuyufvvmauawjmbwlqh
txokdexmdbtgvhpsvsqtmljdx
dcatenrehteoxqdgeueljtrrn
jarteqvtxejfsqddkbuhcysfq
hpdrowssapxtrxhpdxcdhicon
fob=open('c:/Users/username/Desktop/CE151 Python/ass2/grid.txt','r')
text_file = open("grid.txt","r")
listy=[]
for elem in text_file.read().split('\n'):
listy.append(elem)
text_file.close()
You could try this. The lines are stored in the list listy.

Writing a line of row per iteration to file without overwriting the file in python

I have searched this on Stackoverflow and all of the "duplicates" for this topic but it seems remained unanswered. I have tried all these:
Attempt#1:
for word in header:
writer.writerow([word]
Pasted from writing data from a python list to csv row-wise
Attempt#2:
And this one, should have been close but it has a bug:
# Open a file in witre mode
fo = open("foo.txt", "rw+")
print "Name of the file: ", fo.name
Pasted from <http://www.tutorialspoint.com/python/file_writelines.htm>
# 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
seq = ["This is 6th line\n", "This is 7th line"]
# Write sequence of lines at the end of the file.
fo.seek(0, 2)
line = fo.writelines( seq )
# Now read complete file from beginning.
fo.seek(0,0)
for index in range(7):
line = fo.next()
print "Line No %d - %s" % (index, line)
# Close opend file
fo.close()
Pasted from http://www.tutorialspoint.com/python/file_writelines.htm
Attempt#3:
>>>outF = open("myOutFile.txt", "w")
>>>for line in textList:
...    outF.write(line)
...    outF.write("\n")
>>>outF.close()
Pasted from http://cmdlinetips.com/2012/09/three-ways-to-write-text-to-a-file-in-python/
Attempt#4:
with open('file_to_write', 'w') as f:
f.write('file contents')
Pasted from Correct way to write line to file in Python
Attempt#5:
This one which uses the append when writing to file.. but it appends each line at the end of each row. So it would be hard for me to separate all the rows.
append_text = str(alldates)
with open('my_file.txt', 'a') as lead:
lead.write(append_text)
Pasted from Python: Saving a string to file without overwriting file's contents
Can someone help me how to write a newline of row per iteration in a loop to a file without overwriting the file?
data = [1,2,3,4,5]
with open('asd.txt', 'w') as fn:
for i in data:
fn.write(str(i) + '\n') # Add a \n (newline) so the next write will occure in the next line
Content of asd.txt:
1
2
3
4
5
If you want to append to a file use with open('asd.txt', 'a') as fn:
There is 2 ways to do that:
First by adding '\n' character at the end of your output line :
for x in row:
writer.write(x + "\n")
Second by opening file in Append mode, it is going to add lines existing text file but be careful.it's not overwrite the file :
fw = open(myfile.txt,'a')

Print lines from file between header and empty line

I have a file with the following structure: header - data - blank lines - header ... I am trying to print the lines of my datafile between the header and the first blank line. The piece of code I am using doesn't seem to work; do you have any suggestion?
for j in range(0, number_of_angles, 1):
start_line = omega_line_number[j]+5 #start line is the line number after the header
print start_line
for line in range(start_line,num_lines,1): #num_lines is the total number of lines
stripped = line.strip()
if not stripped:
break
print line
I wrote a quick program that works on a text file I made for this. Basically, the text file contains 10 lines containing the word "header" and 20 lines containing the word "body". After that, I have 10 blank lines and repeat the first 30 lines. Here is the code that prints only the body.
if __name__ == '__main__':
# Open the file for reading.
rd_file_name = "../txt/q1.txt"
rd_file = open(rd_file_name, 'r')
# Read through the header
for line in rd_file.readlines():
# Decide what to do based on the content in the line.
if "header" in line.lower():
# Don't print the header
pass
elif line.strip() == "":
# Quit if you see a blank line
break
else:
# We print the body. Lines end with a carriage return, so we don't
# add another one.
print line,
# Clean up
rd_file.close()
line is going to be an integer, and doesn't have a method, strip()

Categories