Reputation: 83
I'm having trouble with this code. It seems like a simple thing, but for some reason no matter what I do it doesn't work.
I'm trying to read a specific line from a file and if that line is empty it prints an error. The problem is that the code doesn't work and keeps returning the same line even if there is something on that line.
To be more specific of what this should do the file has only one line at the begining. "List".
After that everything else is empty. If I print what's in the file it returns 'List \n'.
So, I'm trying to check if the second line (index 1) is blank and then print the error
I tried doing this with a variable lines = [1]
, but that didn't work.
Here is the link to what I tried to do with lines = [1]
https://www.kite.com/python/answers/how-to-read-specific-lines-of-a-text-file-in-python
with open("file.txt", "r") as f:
lines = f.readlines()
for line in lines:
if line == "List: \n" + "\n":
print("\nThere are no lists!")
else:
#Do something
Upvotes: 0
Views: 178
Reputation: 161
Since your line starts with the term "List", you can try
with open("file.txt", "r") as f:
lines = f.readlines()
for line in lines:
if line.startswith("List"):
# Do smth
else:
#empty lines
Update :
Alternatively you can use
if line and line.isspace():
#empty
else :
#Not empty
Upvotes: 1
Reputation: 77407
Just before if line == "List: \n" + "\n"
you could print(repr(line))
and see that it is not the value you are looking for. lines
is a list of lines and will have at most a single newline character and its at the end of the line. The final line may not have a newline depending whether the file terminates with one.
Instead, just look for the contents of a single line. Stripping the line deals with the newline and any inconvenient whitespace on the end and makes up for small mistakes in the file.
with open("file.txt", "r") as f:
lines = f.readlines()
if not lines or lines[0].strip() != "List:":
print("Invalid file")
elif len(lines) < 2 or not(lines[1].strip()):
print("\nThere are no lists!")
You don't need to read the entire file to do this. zip
combines two collections, stopping at the shortest. leveraging that you could
with open("file.txt", "r") as f:
lines = [line.strip() for _, line in zip(range(2), f)]
if not lines or lines[0] != "List:":
print("Invalid file")
elif len(lines) < 2 or not(lines[1].strip()):
print("\nThere are no lists!")
Upvotes: 1
Reputation: 21
def foo():
file = open('file.txt', 'r')
content = file.readlines()
j = 'List' #or word you are looking for
for i in range(len(content)):
if i == 5 and j not in content[i]: # 5 - the 5th line in the txt
return False # or do smth
else:
return True # or do smth
Upvotes: 0