Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 13921

Python reading from a file. Skip empty lines and comments

$
0
0

I'm in a introduction course for Python. I am having a hard time understanding how Python works. I am up to the 6th chapter and each time I find myself setting variables with unintended results but if I switch VarA to where VarB is located. Switch positions, amazingly the program works as intended.

counter = 0with open(text, "r") as file:    lines = file.readlines()for line in lines:    if line.isspace() == False:        counter += 1

This so far counts how many lines there is and skips over the empty lines. I try to check for a comment # line using startswith() but that yields a error to the point isspace() is no longer working. I have tried nesting startswith().

I try putting startswith() in it's own if it counts twice as much. I tried setting counter -= 1 in this if block alone. It yields a error.

Beyond showing me 5 hours of more videos. I really do not understand how startswith() is a function from Python and some how it does not work in the place where you put it.

Every two problems I need to solve that this course introduced, I am constantly rearranging locations of variables and functions. Asking how does a pre-built function fail to respond or be recognized at line 40 of a program. Some computers just guess intended results.

I have tried nested, I have tried putting one function in front of the other. I don't understand how Python fails to reach it's built in functionality.


Viewing all articles
Browse latest Browse all 13921

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>