【发布时间】: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