3

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')
mhawke
  • 84,695
  • 9
  • 117
  • 138
kay oll
  • 29
  • 1
  • 3
  • 2
    `f.close() #optional` - not optional! Not closing your files is like not flushing your poop; it might seem like there aren't any consequences, but the mess you're leaving can cause things to break in nasty ways. Running out of file descriptors, data not being flushed, etc. You don't want to have to deal with that. Always use a `with` block. – user2357112 Oct 11 '15 at 03:35
  • *Line by Line*? Do you need `with open(filename) as f: text = f.readlines()`? If you run this then `text` will be a list and save all data of the file like `['first line\n', 'second line\n']`. – Remi Guan Oct 11 '15 at 03:40
  • While it is good to use 'close', it is not required for simple file reading like this. The file will be closed when the script ends. – hpaulj Oct 11 '15 at 04:08
  • @hpaulj: And if you're not planning to stick around for long, you can get away with not flushing your poop. Please, just do it. – user2357112 Oct 11 '15 at 04:37
  • But Python is one of those modern systems that senses your presence, and flushes when you are gone. http://stackoverflow.com/a/1834766/901925. MInd you, I don't intend to discourage anyone from using `close`, or better yet `with open`. – hpaulj Oct 11 '15 at 05:37

2 Answers2

4

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')
mhawke
  • 84,695
  • 9
  • 117
  • 138
  • I just tried using this instead. But when i ran it, i still got the same output. I'm not sure if it is my spyder that has a problem. Thank you – kay oll Oct 11 '15 at 03:30
  • The output is not helpful. Is there a traceback or more complete error message? How do you know that this block of code is causing the problem? – mhawke Oct 11 '15 at 03:31
  • No, it doesn't show any other error message. It shows the same message every time a run a file and i am not sure why. It just prints out In 1: runfile('/Users/kareemahokunl/example.py', wdir='/Users/kareemahokunl') – kay oll Oct 11 '15 at 03:40
  • @kayoll Do any matters here? What's the output that you wish? – Remi Guan Oct 11 '15 at 03:42
  • @KevinGuan i wish to print out the whole file. Before printing out specific paragraphs. Most of the things i tried, i got it from the python book – kay oll Oct 11 '15 at 03:50
  • Just print out the whole file? What about `with open(filename) as f: print(f.read())`? – Remi Guan Oct 11 '15 at 03:52
  • 1
    You have shown us a function. how do you call the function? How do you call the script? – hpaulj Oct 11 '15 at 04:07
  • @kayoll: I have updated my answer. As hinted at by hpaulj I think that you are not actually calling the function. I have replicated the behaviour that you see in Spyder, so that's probably the reason. – mhawke Oct 11 '15 at 09:07
  • @mhawke thank you very much. i used your edited answer and the answer below to modify the print line in the for loop , and it worked def print_file1(filename): with open(filename) as f: for line in f: print(line, ) # N.B. call the function... print_file1('filename.txt') – kay oll Oct 11 '15 at 15:41
0

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

emvee
  • 4,371
  • 23
  • 23