【问题标题】:Python open modes reset file before writing data [closed]Python打开模式在写入数据之前重置文件[关闭]
【发布时间】:2020-01-15 09:25:50
【问题描述】:

我目前正在尝试使用 with open(file, 'w') as foo: 重置文件内容

但问题是我需要执行两次脚本才能查看文件中的更新数据。

我想要达到的步骤:

(执行脚本)

  1. 清理文件数据
  2. 将数据写入文件
  3. 脚本完成了它的工作

目前脚本可以:

(执行脚本)

  1. 清理文件数据
  2. 将标题写入文件
  3. 脚本完成它的工作

(再次执行脚本)

  1. 将数据写入文件
  2. 现在文件包含更新的数据

我的代码:

def write_updated_data(here_comes_data_as_list):
    header = 'File title here'
    with open(target_file, 'w') as tf:
        tf.write(header + '\n')
        [ tf.write(line + '\n') for line in here_comes_data_as_list ]
    print('Data is written..')

根据fopen手册页模式'w'

Truncate to zero length or create text file for writing.
The stream is positioned at the beginning of the file

如果我理解正确,它将始终在写入之前清理文件。

我的问题为什么它不能正确地做到这一点?它可以写一次吗(就像我的例子写标题并完成它的写)?

更新:

通过强制清理文件也不起作用,它将标头写入文件,然后什么都没有:

def write_updated_data(here_comes_data_as_list):
    header = 'File title here'

    # forcing to clean file
    with open(target_file, 'w') as reset:
        reset.close()

    with open(target_file, 'a') as tf:
        tf.write(header + '\n')
        [ tf.write(line + '\n') for line in here_comes_data_as_list ]
    print('Data is written..')

【问题讨论】:

  • 这里缺少一些东西,我正在执行您的代码,而我正在写入的文件每次运行前都会自行清理。您想在每次执行时清理还是更新文件而不在每次运行时丢失内容?
  • @JimErginbash 我想先清理文件,然后将数据写入其中。在我的情况下,可以丢失数据。
  • 你确定你的函数没有清理 .txt 文件吗?因为我刚刚复制了您的代码 sn-p 并且它确实很干净。如果需要,我可以发布一个答案,您可以如何保留以前执行的旧数据。
  • “更少的代码” – 不是真的。 output = [ ... ] 实际上是更多代码。如果您担心行数,可以在一行中写上for .. in ..: ..。不过话说回来,你是不是缺台词之类的……?阅读您的代码,首先注意到的是未使用的变量output,因此这需要更多的认知努力才能真正破译。
  • @Poli 使用列表推导来处理副作用不仅使代码更难阅读(人们希望使用列表推导来创建新列表),它还会无缘无故地消耗内存和 CPU(建立一个列表并创建一个局部变量不是免费的)。这就是为什么它被认为是不好的做法的原因。 “它的代码更少”并不是让您的代码可读性和效率更低的正当理由(特别是当它实际上不是“更少的代码”时)。

标签: python file logging


【解决方案1】:

这是清理文件:

def write_updated_data(here_comes_data_as_list):
    header = 'File title here'
    with open(target_file, 'w') as tf:
        tf.write(header + '\n')
        output = [ tf.write(line + '\n') for line in here_comes_data_as_list ]
        tf.close()
    print('Data is written..')

write_updated_data(["fdfd","421"])

这是一个为了更新文件而运行的选项:

def file_before():
     r = open(target_file, 'r')
     content = r.read()
     r.close()
     return content

def write_updated_data(here_comes_data_as_list):
    previous_content = file_before()
    header = 'File title here'
    with open(target_file, 'w') as tf:
        tf.write(previous_content) # write the old content first
        tf.write(header + '\n')
        output = [ tf.write(line + '\n') for line in here_comes_data_as_list ]
        tf.close()
    print('Data is written..')

write_updated_data(["fd432432fd","421"])

如果您的列表在后台被其他代码填充,请检查它是否没有返回 None 或空列表 (尝试使用像上面这样的简单字符串)

【讨论】:

  • 除了每次都在文件中写入header之外,这是一个很好的解决方案。
猜你喜欢
  • 2023-02-24
  • 1970-01-01
  • 1970-01-01
  • 2015-09-13
  • 2017-03-21
  • 1970-01-01
  • 2018-07-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多