I am very new to coding, I have a text file that contain data as
Test a value: 1134
Test b value: 2354
Test c value: 4827
And so on I am trying to write a script that will go through this file and increment values of certain tests by 1. For example I need my out put file to look like
Test a value: 1135
Test b value: 2355
Test c value: 4827
I need to do this 1000 time so it will take it forever to do it one by one. Appreciate any help you can provide.
I have tried reading the file and using for loop, not sure what I’m doing wrong, it just keep saying invalid.
f=open('Test.txt' ,mode='r')
h = f.readlines()
for line in h:
list = line[h].split(" ")
for i in line:
if(line.isdigit()):
temp = list[i] 1
list[i] = temp
CodePudding user response:
While I agree with the comments posted to your question, here is a simple solution to help you get started.
with open('file1.txt','r') as f, open('file2.txt','w') as new2:
lines = f.readlines()
print(lines)
for line in lines:
i = int(line.split(':')[-1]) 1
new_line = line.replace(line.split(':')[-1], str(i))
print(new_line)
new2.write(new_line)
First, I read one text file and opened another text file to write (this is to prevent overwriting in your case. You can modify this to read and write to the same file, inplace).
Next, I read the lines of the first text file, which reads into a list. I then take each item of the list, find the number by splitting on ":" (assuming this is your condition since you haven't mentioned otherwise). I increment this number and replace it. I then write the new line into another file.
You may want to consider if all the lines are in the same format. This solution is with that assumption.
Hope this helps you get started!
CodePudding user response:
I don't want to write the code for you. But I'll try to give some suggestions. First, I've made some comments to existing code:
f=open('Test.txt' ,mode='r') # opens file for reading (mode='r')
h = f.readlines() # read all lines into a list. you should close file
# after this line with f.close()
for line in h:
list = line[h].split(" ") # this line is trouble. you should not name
# a variable 'list' as that override the Python list() function.
# this line should really be something like
# mylist = line.split(" ")
for i in line: # the rest of these lines are not very useful
if(line.isdigit()): # recommend deleting them all
temp = list[i] 1 #
list[i] = temp #
Before for line in h
, you need to open a file for writing. Either the same file (if you want to overwrite) or a new output file.
Inside for line in h
, you'll want to increment your number (hint: it will be at index 3 in mylist) and then write the data to a file. Probably you'll want to use str.join() to achieve the inverse of str.split()
Good luck.