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?
#1
Photo 
I dont understand what makes the two "print('# items are:', len(code))" give different results? Does the code change anything in the cfile? And why do i get the result "# of lines: 0" when i know they are 1909 in the file.
   
Reply
#2
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:

cfile = open('/content/drive/MyDrive/Colab_Notebooks/py4e_7.1.txt')
nlines=0
code=0
code=cfile.read()
print('# items are:', len(code))
for line in cfile:
  nlines=nlines+1
code=cfile.read()
print('# of lines:', nlines)
print('# items are:', len(code))
On line 4, you use read(). This reads the entire file into code (as a string of text). The length of a string is the number of characters in it, so when you print # items, it's printing the number of characters in the file.

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.
fiqu likes this post
Reply
#3
Ok, thanks @bowlofred
How would you write it to get both number of characters and number of lines printed out at the same time?
Reply
#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


Possibly Related Threads…
Thread Author Replies Views Last Post
  logging: change log file permission with RotatingFileHandler erg 0 1,016 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 920 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 955 Feb-15-2023, 05:34 PM
Last Post: zsousa
  find some word in text list file and a bit change to them RolanRoll 3 1,518 Jun-27-2022, 01:36 AM
Last Post: RolanRoll
  Problem with importing Python file in Visual Studio Code DXav 7 5,063 Jun-15-2022, 12:54 PM
Last Post: snippsat
  change csv file into adjency list ainisyarifaah 0 1,496 Sep-21-2021, 02:49 AM
Last Post: ainisyarifaah
  Use Python to change a PHP file on my little webpage Pedroski55 0 1,499 Aug-28-2021, 12:42 AM
Last Post: Pedroski55
  How do I change this code for searching duplicats in python ? Eidrizi 0 1,498 Mar-17-2021, 01:34 PM
Last Post: Eidrizi
  how to change the range of read CSV file every time python file runs greenpine 6 4,450 Dec-08-2020, 10:11 PM
Last Post: greenpine
  Change variable in an outside file ebolisa 5 2,620 Nov-11-2020, 04:41 AM
Last Post: ebolisa

Forum Jump:

User Panel Messages

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