[英]Python write function output to file
如果這是一個愚蠢的問題,我很抱歉,但我沒有太多的 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-1-aaaaa)到 changes.txt
您的 'compare_files' 函數不會返回任何內容,因此不會將任何內容寫入文件。 使函數“返回”一些東西,它應該可以工作。
您的函數沒有返回任何內容,因此您正在打印“無”。 如果您希望所有打印都轉到一個文件而不是像默認情況下那樣的標准輸出,您可以像對返回值所做的那樣更改每個打印語句。
或者您可以像在此處完成的那樣對整個程序使用重定向。
因為默認情況下您沒有返回任何內容,該函數返回None
以便反映在您的changes.txt
文件中。 您可以創建一個變量來存儲您想要的輸出並返回它。
def compare_files(file1, file2):
fname1 = file1
fname2 = file2
# Open file for reading in text mode (default mode)
f1 = open(fname1)
f2 = open(fname2)
output_string = ""
# 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)
output_string += "Line added:Line-%d" % line_no + "-" + f1_line + "\n"
# otherwise output the line on file1 and mark it with > sign
elif f1_line != '':
print("Line changed:Line-%d" % line_no + "-" + f1_line)
output_string += "Line changed:Line-%d" % line_no + "-" + f1_line +"\n"
########### 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)
output_string += "Line removed:Line-%d" % line_no + "-" + f1_line +"\n"
# 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()
return output_string
您的compare_files()
只是打印,但不會將任何內容傳遞給調用者。
如果要將一項傳遞給調用者,請使用return
。 您的功能流程到此結束。
如果你想將幾個項目傳遞給調用者,你可以yield
他們。 使用yield
將您的函數變成生成器函數。 調用生成器函數會生成一個可以迭代的生成器對象。
例子:
def produce_strings():
for i in ['a', 'b', 'c']:
yield i + "x"
result = "\n".join(produce_strings())
print(result) # prints a line end separated string made of "ax", "bx" and "cx".
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.