开发者

taking a character input in python from a file?

in python , suppose i have file data.txt . which has 6 lines of data . I want to calculate the no of lines which i am planning to do by going through each character and finding out the number of '\n' in the file . How to take one character input from the file 开发者_JAVA百科? Readline takes the whole line .


I think the method you're looking for is readlines, as in

lines = open("inputfilex.txt", "r").readlines()

This will give you a list of each of the lines in the file. To find out how many lines, you can just do:

len(lines)

And then access it using indexes, like lines[3] or lines[-1] as you would any normal Python list.


You can use read(1) to read a single byte. help(file) says:

read(size) -> read at most size bytes, returned as a string.

If the size argument is negative or omitted, read until EOF is reached. Notice that when in non-blocking mode, less data than what was requested may be returned, even if no size parameter was given.

Note that reading a file a byte at a time is quite un-"Pythonic". This is par for the course in C, but Python can do a lot more work with far less code. For example, you can read the entire file into an array in one line of code:

lines = f.readlines()

You could then access by line number with a simple lines[lineNumber] lookup.

Or if you don't want to store the entire file in memory at once, you can iterate over it line-by-line:

for line in f:
    # Do whatever you want.

That is much more readable and idiomatic.


It seems the simplest answer for you would be to do:

for line in file:
    lines += 1
    # do whatever else you need to do for each line

Or the equivalent construction explicitly using readline(). I'm not sure why you want to look at every character when you said above that readline() is correctly reading each line in its entirety.


To access a file based on its lines, make a list of its lines.

with open('myfile') as f:
    lines = list(f)

then simply access lines[3] to get the fourth line and so forth. (Note that this will not strip the newline characters.)

The linecache module can also be useful for this.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜