从文本文件中删除单个值

时间:2018-02-24 22:47:25

标签: python python-3.x

我正在创建一个程序,在file.txt中存储很多值。我希望能够从文件中删除一些值(如每分钟1个值)。 (对于存储方法,如果有用,我每行存储1个值。)

有一个半解决方案创建第二个文件但我的问题是我的程序必须继续将数据存储在file.txt中,然后必须从同一个file.txt删除一些数据。

我有时也必须停止程序,并且我不希望通过将其放入字符串中来丢失数据。

有没有人有解决方案?

1 个答案:

答案 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