Python запись функции вывода в файл - PullRequest
0 голосов
/ 26 февраля 2019

Извините, если это глупый вопрос, но у меня немного опыта работы с 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

, но в файл changes не выводится только None.txt

Я использую "обходной путь" sys.stdout, но интересноесть какой-то другой способ вместо перенаправления вывода на печать.

Если в выводе функции я задаю return вместо print, тогда я получаю только первую строку вывода (строка изменена: Line-1-aaaaa) в changes.txt

Ответы [ 4 ]

0 голосов
/ 26 февраля 2019

Ваш 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".
0 голосов
/ 26 февраля 2019

Ваша функция не возвращает ничего, поэтому вы печатаете «Нет».Если вы хотите, чтобы вся печать шла в файл, а не в stdout, как это делается по умолчанию, вы можете изменить каждое выражение печати, как вы сделали, на возвращаемое значение.

Или вы можете использовать перенаправление для всей программы, как сделанов здесь .

0 голосов
/ 26 февраля 2019

Поскольку по умолчанию вы ничего не возвращаете, функция возвращает 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
0 голосов
/ 26 февраля 2019

Ваша функция «сравнение_файлов» ничего не возвращает и поэтому ничего не записывается в файл.Сделайте функцию ' return ' чем-то, и она должна работать.

...