简体   繁体   中英

Line by Line reading of text files on python 3.4

I save a book as a text file on my python and i am trying to read the file line by line. I have tried using this

def print_file1(filename):
    f = open(filename, 't')
    for line in f:
        print(line, end = '')
    f.close() #optional

But, everytime i try running this, it doesn't work. This is what i get as my output

runfile('/Users/kareemahokunlola/example.py', wdir='/Users/kareemahokunlola')

By itself 't' is not a valid mode for opening a file.

You could specify mode as rt . If you omit the mode it will default to 'r' (read in text mode) which is probably sufficient for your purposes. (If your file contains binary data, you can add the 'b' to the mode.)

I would also consider writing it like this with a with statement:

def print_file1(filename):
    with open(filename) as f:
        for line in f:
            print(line, end = '')

This has the advantage that you don't need to worry about closing the file - it will happen automatically upon exit from the with statement, for whatever reason.


Update

So you are executing this code from within the Spyder IDE? When you successfully run a script Spyder will display:

runfile('/Users/kareemahokunlola/example.py', wdir='/Users/kareemahokunlola')

in the console. This is what you are seeing, so your script is running without error.

There are a couple of possibile explanations:

  1. You are not calling the function print_file1() from within your script. The script runs without error, but the file is not displayed because print_file1() is not called. This is the most likely explanation because your original code that attempts to open the file with mode 't' will raise an exception, and that exception will be logged to the console. But the error is not displayed, hence it is probable that the function is not actually called.
  2. You are calling print_file1() but the file is empty. In this case the "runfile()" message will be displayed because the script ran successfully, but nothing else is seen because the file is empty.

Try adding a call to print_file1() after you define the function:

def print_file1(filename):
    with open(filename) as f:
        for line in f:
            print(line, end = '')

# N.B. call the function...
print_file1('/etc/hosts')

I would put my money on the following statement:

print(line, end = '')
            ^^^^^^^^

You're telling Python to print the line without a newline, effectively concatenating all individual lines into a single line on the screen.

See https://docs.python.org/3/library/functions.html#print

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM