(Python) len traceback, error in .rstrip

Asked 2 years ago, Updated 2 years ago, 111 views

name = input ('Enter file name: ')
if len(name) > 1 :
    name = 'mbox-short.txt'
filename = open(name)

for line in filename :
    if 'From ' in line :
        print(line.rstrip)

    else :
        continue


print(filename)


(1)

I'm practicing the code to filter emails in the document through Cocera. I was lazy to type the file name, so I used the len code that Professor Kosera also used, but for some reason, there is a message that I couldn't find the file or directory due to traceback in the fourth line variable. Why is this problem even though I didn't enter the wrong file name? What am I doing wrong?

(2)

If you don't use .rstrip, you can find and print out words without any problems, but if you put .rstrip, The value has been changed to built-in method rstrip of strip object at 0x03DSEA88 and is being output. Whether you get the price you want. Whether you get it or not, the message <_io.TextIOWrappername='mbox-short.txt'mode='r'encoding='cp1252'> is printed at the end, how do I get rid of these messages and get the value I want to get? What's wrong with this problem?

Please give me some advice.

python len rstrip

2022-09-22 19:31

1 Answers

(1)

I think it'd be nice if you put up the backtrace as well.

Traceback occurs, prompting you to say that the file, directory, could not be found.When you say , it seems that an exception occurred in filename = open(name). open() causes the IOError exception if the file is not in the path you entered. If you do not receive this through try~exception, the program will exit and the traceback will be printed.

If the purpose is to create a file with name, you need to set the mode as below.

filename = open(name, "w")

(2)

rstrip is a function. Therefore, it is called only when it is opened and closed in parentheses, such as rstrip(). So try modifying it like print(line.rstrip().

In addition, print(filename), <_io.TextIOWrapper name='mbox-short.txt' mode='r' encoding='cp1252'> is displayed because the filename=openname became a file. Of course, you can erase this output code if you want to raise it.


2022-09-22 19:31

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.