Reputation: 409
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!
Upvotes: 0
Views: 433
Reputation: 765
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']]
Upvotes: 2
Reputation: 1114
# 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...i.e., rest[0]
is the first char, rest[1]
the next, etc. Be aware that you will capture newlines too this way.
Upvotes: 1