python - 从文本文件中删除单个值

标签 python python-3.x

我正在创建一个在 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/

相关文章:

python - 找到所有具有一定数量的变量和次数的单项式

python - 更改 cx_Freeze 脚本的图标

python - 用 DataFrame 的 NaN 替换特定范围的值

python - 如何使用输入 *.txt 文件绘制一个非常简单的条形图(Python、Matplotlib)?

python - 如何从 Python 的字典列表中删除基于选定键的重复字典?

python - 递归Python函数的值修 retrofit 饰器

python - 如何通过 PyCharm 安装 PyGObject

python - 如何从行中获取数据到元组中

python-3.x - 将父列的相同值更新为 Pandas 数据框中的子列表值

python - 使用自动编码器重建潜在空间