Nov-03-2021, 10:23 PM
(Nov-03-2021, 10:03 PM)fiqu Wrote: Ok, thanks @bowlofred
How would you write it to get both number of characters and number of lines printed out at the same time?
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.
with open('/content/drive/MyDrive/Colab_Notebooks/py4e_7.1.txt') as cfile: entire_file = cfile.read() print(f"The file has {len(entire_file)} characters") for line in entire_file.splitlines(): total_lines = 0 for line in cfile: total_lines += 1 print(f"The file has {total_lines} lines")