Having trouble with a string... - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Having trouble with a string... (/thread-13458.html) |
Having trouble with a string... - malonn - Oct-16-2018 I have written the contents of a dictionary to a text file. Each key stores a list. I'm having trouble reading the list, however. I only want what was the second item on the list. Here's some code and the contents of the text file that the script reads from: def write_dumps(self): dmp = self.scan_dumps() i = 0 with open('practice_gui_2.ini', 'w') as f: while i < len(dmp): s = str(dmp[i]) f.write(f'{s}\n') i += 1 def get_size(self): '''Reads fro Ini created by "scan_dumps()" and gets total size of all .DMP files to display in the GUI.''' with open('practice_gui_2.ini', 'r') as f: s = f.readline() l = s.find(',') ... ['C:\\Games\\Steam\\dumps\\assert_steam.exe_20181011101734_1.dmp', 451628] I can't figure out how to find the comma and then read only the numbers after the comma. I don't want the brackets or the spaces. Thanks in advance for any help. -malonn RE: Having trouble with a string... - malonn - Oct-16-2018 I think I have it figured. Here's what works for me if anyone is interested and if anyone can see room for improvement: with open('practice_gui_2.ini', 'r') as f: tsize = 0 for line in f: print(line) lc = line.find(',') stn = '' for d in line[lc + 2::]: if d.isdigit(): stn += d tsize += int(stn) print(tsize) RE: Having trouble with a string... - ichabod801 - Oct-16-2018 You can use join to make the code simpler: stn = ''.join([char.isdigit() for char in line[lc + 2:]]) RE: Having trouble with a string... - marienbad - Oct-16-2018 with open('practice_gui_2.ini', 'r') as f: tsize = 0 for line in f: data = line.split(",") print data[1] RE: Having trouble with a string... - malonn - Oct-16-2018 (Oct-16-2018, 02:53 PM)ichabod801 Wrote: You can use join to make the code simpler:Gives the following error TypeError: sequence item 0: expected str instance, bool found (Oct-16-2018, 02:57 PM)marienbad Wrote:Thanks, but that approach keep leading whitespace and trailing bracket.with open('practice_gui_2.ini', 'r') as f: tsize = 0 for line in f: data = line.split(",") print data[1] RE: Having trouble with a string... - marienbad - Oct-16-2018 Just add: dd = data[1] print dd[1:-2]at the end to remove them RE: Having trouble with a string... - ichabod801 - Oct-16-2018 Well, sorry. That was bad. stn = ''.join([char for char in line[lc + 2:] if char.isdigit()]) RE: Having trouble with a string... - malonn - Oct-16-2018 (Oct-16-2018, 05:03 PM)marienbad Wrote: Just add:Works like a charm. Thanks. (Oct-16-2018, 06:37 PM)ichabod801 Wrote: Well, sorry. That was bad.Works like a charm as well, thanks. |