Python Forum
(Beginners problem) Does file change during this code?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
(Beginners problem) Does file change during this code?
#4
(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")
Reply


Messages In This Thread
RE: (Beginners problem) Does file change during this code? - by bowlofred - Nov-03-2021, 10:23 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  How can I write formatted (i.e. bold, italic, change font size, etc.) text to a file? JohnJSal 12 27,977 Feb-13-2025, 04:48 AM
Last Post: tomhansky
  [SOLVED] [Linux] Write file and change owner? Winfried 6 1,505 Oct-17-2024, 01:15 AM
Last Post: Winfried
  What does .flush do? How can I change this to write to the file? Pedroski55 3 1,324 Apr-22-2024, 01:15 PM
Last Post: snippsat
  logging: change log file permission with RotatingFileHandler erg 0 2,464 Aug-09-2023, 01:24 PM
Last Post: erg
  How can I change the uuid name of a file to his original file? MaddoxMB 2 2,111 Jul-17-2023, 10:15 PM
Last Post: Pedroski55
  unittest generates multiple files for each of my test case, how do I change to 1 file zsousa 0 1,621 Feb-15-2023, 05:34 PM
Last Post: zsousa
  find some word in text list file and a bit change to them RolanRoll 3 2,351 Jun-27-2022, 01:36 AM
Last Post: RolanRoll
  Problem with importing Python file in Visual Studio Code DXav 7 9,605 Jun-15-2022, 12:54 PM
Last Post: snippsat
  change csv file into adjency list ainisyarifaah 0 1,866 Sep-21-2021, 02:49 AM
Last Post: ainisyarifaah
  Use Python to change a PHP file on my little webpage Pedroski55 0 1,883 Aug-28-2021, 12:42 AM
Last Post: Pedroski55

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020