简体   繁体   English

Python写函数输出到文件

[英]Python write function output to file

I'm sorry if this is silly question but I have no much Python experience如果这是一个愚蠢的问题,我很抱歉,但我没有太多的 Python 经验

I have function for comparing files我有比较文件的功能

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()

I want to print function output to a text file我想将函数输出打印到文本文件

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

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

i tried following:我试过以下:

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

f.write(str(result))

f.close

but only None is printed to changes.txt但只有 None 被打印到 changes.txt

I'm using "workaround" sys.stdout but wonder is there any other way instead of redirecting print output.我正在使用“解决方法” sys.stdout 但想知道是否有其他方法而不是重定向打印输出。

If in function output I specify return instead of print then I'm getting only first output line (Line changed:Line-1-aaaaa) to changes.txt如果在函数输出中我指定 return 而不是 print 那么我只得到第一个输出行(行更改:Line-1-aaaaa)到 changes.txt

Your 'compare_files' function does not return anything and therefore nothing is written to the file.您的 'compare_files' 函数不会返回任何内容,因此不会将任何内容写入文件。 Make the function ' return ' something and it should work.使函数“返回”一些东西,它应该可以工作。

Your function isn't returning any thing so you are printing 'None'.您的函数没有返回任何内容,因此您正在打印“无”。 If you want all the print to go to a file instead of stdout like it does by default you can chane each print statement like you did to the return value.如果您希望所有打印都转到一个文件而不是像默认情况下那样的标准输出,您可以像对返回值所做的那样更改每个打印语句。

Or you can use redirection for the whole program like done in here .或者您可以像在此处完成的那样对整个程序使用重定向。

Because you are not returning anything by default the function returns None so that is reflected in your changes.txt file.因为默认情况下您没有返回任何内容,该函数返回None以便反映在您的changes.txt文件中。 you can create a variable that stores the output that you wanted and returns it.您可以创建一个变量来存储您想要的输出并返回它。

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

Your compare_files() just prints, but doesn't pass anything to its caller.您的compare_files()只是打印,但不会将任何内容传递给调用者。

If you want to pass one item to the caller, you use return .如果要将一项传递给调用者,请使用return The flow of your function ends there.您的功能流程到此结束。

If you want to pass several items to the caller, you yield them.如果你想将几个项目传递给调用者,你可以yield他们。 Using yield turns your function ito a generator function.使用yield将您的函数变成生成器函数。 Calling a generator function produces a generator object which can be iterated over.调用生成器函数会生成一个可以迭代的生成器对象。

Example:例子:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM