How to append characters between two strings in existing .txt file using python -
i trying add "," between lot of data in .txt file , want delete second rows.
this example of txt file
1 1 139 178 128 83 140 140 87 87 2 1 199 204 130 111 198 198 89 89 3 1 188 182 107 120 183 183 109 109 ......
'....' here means thousand of data.
and want print result in new .txt file
this results wanted.
1, 139, 178, 128, 83, 140, 140, 87, 87 2, 199, 204, 130, 111, 198, 198, 89, 89 3, 188, 182, 107, 120, 183, 183, 109, 109 .....
i hope 1 here can me problem , appreciate much!
thanks!
first, iterate on lines:
with open(filename) f: line in f: # can process line here
now lets see can each line:
words = line.split() # split on whitespace del words[1] # remove word @ index 1 joined = ", ".join(words) print(joined) # can print stdout, or write file
updates after followup:
once open file, f
in example, can treat iterator of lines. that's why for line in f
works. can manipulate other iterator want has side effects , here's why:
list in memory
if have list in memory , want access items, it's easy enough to slice , iterate on although there inefficiencies involved:
lines = [...] # list of lines in memory # inefficient - creates expensive intermediate lists, 1 each slice, , 1 concatenated list line in lines[2:12] + lines[15:22]: # process line # more efficient - creates less intermediate lists, 1 each slice itertools import chain line in chain(lines[2:12, lines[15:22]): # process line
if use islice
beware it's more expensive - islice
can consume entire list until reaching slice, instead of slicing efficiently.
why doesn't islice work f
f
indeed iterator of lines, goes forward. great - can process file billions of lines , not use memory - means once islice
consumes lines that's it. need find way filter lines need without "random access", without needing jump arbitrary numbers of steps forwards , backwards in sequence. can if add line indexes iteration.
here's trivial way:
def line_index_is_interesting(index): return 2 <= index <= 11 or 15 <= index <= 21 open(filename) f: index = 0 line in f: if line_index_is_interesting(index): # process line index += 1
this way process each line once, never using lot of memory. adding state of 'index' variable can make decision easily.
this sounds useful - built-into python?
yes, it's built-in function called enumerate:
with open(filename) f: i, line in enumerate(f): if line_index_is_interesting(i): # process line
Comments
Post a Comment