【问题标题】:Python write function output to filePython将函数输出写入文件
【发布时间】:2019-02-26 09:24:35
【问题描述】:

如果这是个愚蠢的问题,我很抱歉,但我没有太多 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,但想知道是否有其他方法可以代替重定向打印输出。

如果在函数输出中我指定返回而不是打印,那么我只会得到第一个输出行(行已更改:Line-1-aaaaa)到 changes.txt

【问题讨论】:

  • return 语句在 compare_files 函数中丢失。
  • 我写了一个问题,如果我添加 return 则只返回一行
  • @script 如果你想“返回”几个条目,你必须yield他们,把函数变成一个生成器函数并像这样对待它。
  • 您似乎缺少很多基本知识...对您来说最简单的方法,我相信是在shell中进行重定向。例如python your_script.py &gt; output_file.txt。另一种简单的方法是,而不是 printing 在您的比较函数中,将该行附加到列表中。在函数结束时,返回列表。然后您将返回函数作为“比较结果”(以文本形式),然后调用者可以将其保存到文件中(或打印或其他)。 (发电机等现在对你来说似乎太复杂了)

标签: python string-comparison


【解决方案1】:

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

【讨论】:

  • 我写了一个问题,如果我添加 return 则只返回一行
【解决方案2】:

因为默认情况下您没有返回任何内容,所以该函数会返回 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

【讨论】:

    【解决方案3】:

    你的函数没有返回任何东西,所以你打印的是“无”。如果您希望所有打印都转到文件而不是像默认情况下那样转到标准输出,您可以像对返回值所做的那样更改每个打印语句。

    或者您可以像在here 中那样对整个程序使用重定向。

    【讨论】:

      【解决方案4】:

      您的 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".
      

      【讨论】:

        猜你喜欢
        • 2015-01-21
        • 1970-01-01
        • 1970-01-01
        • 2020-07-03
        • 1970-01-01
        • 2016-03-18
        • 2019-10-12
        • 1970-01-01
        • 2016-05-03
        相关资源
        最近更新 更多