gpt4 book ai didi

Python将函数输出写入文件

转载 作者:太空宇宙 更新时间:2023-11-04 04:18:52 24 4
gpt4 key购买 nike

如果这是个愚蠢的问题,我很抱歉,但我没有太多 Python 经验

我有比较文件的功能

def compare_files(file1, file2):
fname1 = file1
fname2 = file2

# Open file for reading in text mode (default mode)
f1 = open(fname1)
f2 = open(fname2)
# Print confirmation
#print("-----------------------------------")
#print("Comparing files ", " > " + fname1, " < " +fname2, sep='\n')
#print("-----------------------------------")

# Read the first line from the files
f1_line = f1.readline()
f2_line = f2.readline()

# Initialize counter for line number
line_no = 1

# Loop if either file1 or file2 has not reached EOF

while f1_line != '' or f2_line != '':

# Strip the leading whitespaces
f1_line = f1_line.rstrip()
f2_line = f2_line.rstrip()

# Compare the lines from both file
if f1_line != f2_line:

########## If a line does not exist on file2 then mark the output with + sign
if f2_line == '' and f1_line != '':
print ("Line added:Line-%d" % line_no + "-"+ f1_line)
#otherwise output the line on file1 and mark it with > sign
elif f1_line != '':
print ("Line changed:Line-%d" % line_no + "-"+ f1_line)


########### If a line does not exist on file1 then mark the output with + sign
if f1_line == '' and f2_line != '':
print ("Line removed:Line-%d" % line_no + "-"+ f1_line)
# otherwise output the line on file2 and mark it with < sign
#elif f2_line != '':
#print("<", "Line-%d" % line_no, f2_line)

# Print a blank line
#print()

#Read the next line from the file
f1_line = f1.readline()
f2_line = f2.readline()
#Increment line counter
line_no += 1

# Close the files
f1.close()
f2.close()

我想将函数输出打印到文本文件

result=compare_files("1.txt", "2.txt")

print (result)
Line changed:Line-1-aaaaa
Line added:Line-2-sss
None

我试过以下:

f = open('changes.txt', 'w')

f.write(str(result))

f.close

但只有 None 被打印到 changes.txt

我正在使用“解决方法”sys.stdout,但想知道是否有其他方法可以代替重定向打印输出。

如果在函数输出中我指定 return 而不是 print 那么我只会将第一行输出 (Line changed:Line-1-aaaaa) 更改为 changes.txt

最佳答案

您的“compare_files”函数不会返回任何内容,因此不会向文件写入任何内容。使函数“返回”成为某种东西,它应该可以工作。

关于Python将函数输出写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54882158/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com