🔒 Locked
Reading files with Python
Advertisement
Original Post
I'm pretty new to python. I'm having trouble getting python to read and display what a files says. Like a txt file. Anyone know what I have to type to get python to look for the file, read, and display what the file says? edit: I know how to make python read files, I just want it to display what it says.
The newline character at the end of each ... line, is included in the strings you are iterating on. And print itself does print a newline too. So you get two newlines.
Fix: Either remove the newline from the strings as you go:
Alternatively:
Or have print not add a newline
Note that you can use file instead of open.
Fix: Either remove the newline from the strings as you go:
myfile = open('bla.txt')for line in myfile: print line[:-1]Alternatively:
myfile = open('bla.txt')for line in myfile: print line.rstrip("\r\n")Or have print not add a newline
myfile = open('bla.txt')for line in myfile: print line,Note that you can use file instead of open.
The Python Documentation is the definite resource if you want to know how to do something in Python, and google is the second.
EDIT:
And by the way, I think it's prefered to use list comprehension and such instead of for loops, e.g:
I also recommend Dive Into Python if you already know how to program; it's a great book.
EDIT:
And by the way, I think it's prefered to use list comprehension and such instead of for loops, e.g:
file = open(...)print "".join([line for line in file])I also recommend Dive Into Python if you already know how to program; it's a great book.
Quote:That applies mostly if you want to construct a list with a simple loop. In this case it seems that one just wants to print out stuff, and I don't see list comprehensions that suitable.
Original post by bytecoder
And by the way, I think it's prefered to use list comprehension and such instead of for loops
Quote:
Original post by bytecoder
And by the way, I think it's prefered to use list comprehension and such instead of for loops, e.g:file = open(...)print "".join([line for line in file])
There is no point in constructing a list comprehension : a file is a lazy iterable object. As such, it is designed to allow efficient for loops.
if you want the file as a single string, just do f.read().
If you want a list of strings, just do f.readlines() or even list(f) (build a list from an iterable).
Topic Locked
This topic has been locked by a moderator. New replies are not allowed.
Sign in to reply to this topic.
Advertisement