(Beginners problem) Does file change during this code?
(Beginners problem) Does file change during this code?
|
||||
Nov-03-2021, 09:51 PM
Please don't use images of code. Paste it as text between python tags (use the python button in the editor). Here's your code:
In the for loop on line 6, assigning from the open file will read in a line at a time. But the previous read() has consumed everything. There are no lines remaining. One line 8, you again try to read the entire file into code . But since the file has been read, it's at EOF and this just returns the empty string. Since the loop didn't run, nlines is 0 and since you overwrite code with an empty string, len(code) is zero. Get rid of the two cfiile.read() lines and the loop should at least run and give you the number of lines in the file.
Nov-03-2021, 10:03 PM
Ok, thanks @bowlofred
How would you write it to get both number of characters and number of lines printed out at the same time?
Nov-03-2021, 10:23 PM
(Nov-03-2021, 10:03 PM)fiqu Wrote: Ok, thanks @bowlofred How important is getting the character length? Often it's easier to just read the data line-by-line. But that mechanism lets python split (and discard) the newline characters. Different formats might have different newlines. Doing it that way wouldn't be able to tell between a unix-style <LF> and a windows style <CR><LF>. So my first thought is to not try. But if you really had to, you have a couple of ways. * read in the entire file (count the characters), then split it into lines. Fine for "regular" files * read in the file in chunks (count the characters), then re-read it into lines. May be necessary for "huge" files to avoid memory issues.
| ||||
|
Users browsing this thread: 1 Guest(s)