I have some troubles with file editing. I want to know how can I make my text in example1 look like text in example2 (simply want just to add a number , in the start of each line, numbers must increase by 1 in each line). Those text in images I've pinned is just for example, it can be anything, the main is adding nums in the start!!! enter image description here enter image description here
CodePudding user response:
Since this is CSV data I'd use the csv module:
import csv
with open("test.csv", newline="") as f:
rows = list(csv.reader(f))
with open("test.csv", "w") as f:
csv.writer(f).writerows([i] row for i, row in enumerate(rows, 1))
% cat test.csv
foo,bar,baz
ola,qux,quux
asdf,jkl,qwert
% python test.py
% cat test.csv
1,foo,bar,baz
2,ola,qux,quux
3,asdf,jkl,qwert
CodePudding user response:
To edit text file as you requested you can use below script:
with open("name.txt", 'r') as names:
with open("name5.txt", 'a') as updatedNames:
for i,name in enumerate(names):
updatedNames.write(str(i) ',' name.rstrip() '\n')
Before script
Enes
Nakiro
After script
1,Enes
2,Nakiro
CodePudding user response:
You can open a stream on it and read line by line, writing them with the appended number to a new file. Doing it with streaming allows you to not have to load the whole file in memory.
Alternatively you could use regex to match for '\n' with words following, getting the index of each max and proceeding to loop on that with a for starting from the end of the file, inserting the number using the total number of regex matches - 1 per incrementation.
I would recommend you the first approach, since the OS reads the file chunk by chunk it will be very fast and optimized memory wise to proceed that way.
something along those lines :
file_path = #your_file
index = 1
line = None
with open(file_path) as f1:
with open(new_path) as f2:
while((line = f1.readline()) is not None):
f2.writeline(index "," line)
index
This should work. Refactor it according to your needs. Be sure to check how the reading method behave exactly, does it return the line without the newline character or not ? Depending on that use a write or writeline method for the new file.
