【问题标题】:How to write full output to a file in python without appending如何在不附加的情况下将完整输出写入python中的文件
【发布时间】:2019-05-16 05:42:30
【问题描述】:

我在for 循环之后调用cFile(string),它将返回几个字符串。当我使用 'a+' 时,它会将所有字符串数据(20 行)记录到现有文件中,但是当我使用 'w+' 时,它只写入 1 行(第一个循环输出)。所以,为了测试,我添加了 print 语句,我看到它在两种情况下都打印了所有 20 行。

def cFile(input_file):
    f = open(r'c:\logs\temp\file.log','a+') \\20lines output but appending.
    f.write(input_file)
    f.close();

def cFile(input_file):
    f = open(r'c:\logs\temp\file.log','w+') \\1 line output
    f.write(input_file)
    f.close();

有没有办法在使用 a+ 写入所有数据之前清理日志文件? 或者是否可以使用 w+ 将整个输出写入文件?我只想要文件中运行的输出。

For循环

 for dirpath, dirnames, filenames in os.walk(p):
    my_paths.append(filenames)
    for filename in filenames:
            string_output='hello'
#print (string_output);
cFile(string_output)

【问题讨论】:

  • for 循环是什么样的?看到这会有所帮助。
  • @JonahBishop 添加了一个示例。
  • @Prime,请告诉更多像 20 行 是什么意思?这些是路径还是只是文件名?您的最终目标是使用 w+file.log 中包含所有 20 个文件名,对吗✅?

标签: python python-3.x python-2.7


【解决方案1】:

取决于您的应用程序,但我不认为每次都重新打开您的文件是一个很好的实现。考虑使用全局记录器,在设置阶段清除文件,并使用 a+ 标志设置记录器。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-13
    • 1970-01-01
    • 2021-12-17
    相关资源
    最近更新 更多