我正在创建一个程序,在file.txt
中存储很多值。我希望能够从文件中删除一些值(如每分钟1个值)。 (对于存储方法,如果有用,我每行存储1个值。)
有一个半解决方案创建第二个文件但我的问题是我的程序必须继续将数据存储在file.txt
中,然后必须从同一个file.txt
删除一些数据。
我有时也必须停止程序,并且我不希望通过将其放入字符串中来丢失数据。
有没有人有解决方案?
答案 0 :(得分:1)
name = 'values' # Change to whatever your file is called
directory = '' # Change to your directory (inside a folder etc.:). Leave blank if none
filetype = '.txt' # Change to your file type
data = []
repeat = 0
with open(directory+name+filetype,'r') as file: # Gets data from file
for line in file:
for word in line.split('\n'):
if repeat % 2 == 0: # Doesn't add every other term, which are empty strings
data.append(word)
repeat += 1
del data[0] # Change to delete whatever item of your list
file = open(directory+name+filetype,"w") # Opens and clears the file
for values in data: # Writes to file
file.write(values + '\n')
file.close() # Closes the file