简体   繁体   中英

Read file character by character starting at a particular line

I am using tkinter to bring up a dialog box where the user can choose a file. I want to parse that file starting on line 11. The file looks like this:

(115,147)
(6,145)
(44,112)
(17,72)
(112,1)
(60,142)
(47,158)
(35,43)
(34,20)
(38,33)
11101111110111011111111110111111111111111111111011111111111111110111111111
111101111101111a11011122112011222222211112111221221111101111111111110111ab
..more down here

How do I retrieve each character when they are not separated by spaces? I know I have to start off like this:

# Bring up save dialog box
file_path = filedialog.askopenfilename(filetypes=[("Text files","*.txt")])

# Check if user clicked cancel
if file is None or file is '':
    return False

# Read from file
with open(file, 'r') as f:
    # Do something here with f.read()

I want to get these numbers in a list (each at their own index):

11101111110111011111111110111111111111111111111011111111111111110111111111
111101111101111a11011122112011222222211112111221221111101111111111110111ab

Any help would be appreciated, thank you!

Firstly, you need to read() data from the file, and then split by newlines to get a list of lines in the file:

lines=f.read().split("\n")

If you only need from line 11 to the end, you can use:

lines=lines[10:]

And then iterate through it, using list() to split into characters:

characters=[list(line)for line in lines]

Output:

[['1', '1', '1', '0', '1', '1', '1', '1', '1', '1', '0', '1', '1', '1', '0', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '0', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '0', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '0', '1', '1', '1', '1', '1', '1', '1', '1', '1'], ['1', '1', '1', '1', '0', '1', '1', '1', '1', '1', '0', '1', '1', '1', '1', 'a', '1', '1', '0', '1', '1', '1', '2', '2', '1', '1', '2', '0', '1', '1', '2', '2', '2', '2', '2', '2', '2', '1', '1', '1', '1', '2', '1', '1', '1', '2', '2', '1', '2', '2', '1', '1', '1', '1', '1', '0', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '0', '1', '1', '1', 'a', 'b']]
# consume 10 lines
for _ in range(10):
    f.readline()

# read one character at a time
# f.read(1) will return '' when you reach eof
c = f.read(1)
while c:
    # do something with c
    c = f.read(1)

For that matter, since lists and strings are sort of the same in python, you could just say

# consume 10 lines
for _ in range(10):
    f.readline()

rest = f.read()

and then rest would be a list/string with everything in it...ie, rest[0] is the first char, rest[1] the next, etc. Be aware that you will capture newlines too this way.

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