问题
I have a text file named 1.txt which contains the following:
123456
011111
02222
03333
and I have created a python code which copy the first line to x number of folders to file number.txt then copy the second to x number of folders:
progs = int(raw_input( "Folders Number : "))
with open('1.txt', 'r') as f:
progs2 = f.read().splitlines()
progs3 = int(raw_input( "Copy time for each line : "))
for i in xrange(progs):
splis = int(math.ceil(float(progs)/len(progs3)))
with open("{0}/number.txt".format(pathname),'w') as fi:
fi.write(progs2[i/splis])
I want to edit the code to remove the line after copying it to the specified number of folder; like when the code copy the number 123456 I want it to be deleted from the file so when I use the program again to continue from the second number.
Any idea about the code?
回答1:
I'd like to write this as a comment but I do not have the necessary points to do that so I'll just write an answer. Adding up on Darren Ringer's answer.
After reading the line you could close the file and open it again overwriting it with the old content except for the the line which you want to remove, which has already been described in this answer:
Deleting a specific line in a file (python)
Another option would be to use in-place Filtering using the same filename for your output which would replace your old file with the filtered content. This is essentially the same. You just don't have to open and close the file again. This has also already been answered by 1_CR in the following question and can also be found at https://docs.python.org/ (Optional in-place filtering section):
Deleting a line from a text file
Adapted to your case it would look something like this:
import fileinput
import sys, os
os.chdir('/Path/to/your/file')
for line_number, line in enumerate(fileinput.input('1.txt', inplace=1)):
if line_number == 0:
# do something with the line
else:
sys.stdout.write(line) # Write the remaining lines back to your file
Cheers
回答2:
You could load all the lines into a list with readlines(), then when you get a line to work with simply remove it from the list and then write the list to the file. You will be overwriting the entire file every time you perform a read (not just removing the data inline) but there is no way to do it otherwise while simultaneously ensuring the file contents are up-to-date (Of which I am aware).
来源:https://stackoverflow.com/questions/26573459/remove-line-from-a-text-file-after-read