我正在创建一个在 file.txt
中存储大量值的程序。我希望能够从文件中删除一些值(例如每分钟 1 个值)。 (对于存储方法,如果有帮助的话,我每行存储 1 个值。)
有一个创建第二个文件的半解决方案,但我的问题是我的程序必须继续将数据存储在 file.txt
中,然后必须从同一个 中删除一些数据文件.txt
.
有时我还必须停止程序,并且我不想因为将数据放入字符串中而丢失数据。
有人有解决办法吗?
最佳答案
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
关于python - 从文本文件中删除单个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48968435/