繁体   English   中英

如何将 Python Shell 写入输出文本文件?

[英]How to write Python Shell to an output text file?

我需要将我的 Python shell 写入输出文本文件。 我将其中一些写入输出文本文件,但我现在需要的只是将行数和每行中的数字添加到我的输出文本文件中。

我试图在 for 循环之外添加另一个 for 循环。 我试过把它放在 for 循环中,但它很复杂。

数字的文本文件列表:

1.0,    1.12, 1.123
1.0,1.12,1.123
1

代码:

import re
index = 0
comma_string = ', '
outfile = "output2.txt"
wp_string = " White Space Detected"
tab_string = " tab detected"
mc_string = " Missing carriage return"
ne_string = " No Error"
baconFile = open(outfile,"wt")
with open("Version2_file.txt", 'r') as f:
    for line in f:
        flag = 0
        carrera = ""
        index = index +1
        print("Line {}: ".format(index))
        baconFile.write("Line {}:  ".format(index))
        if " " in line:                         #checking for whitespace
            carrera = carrera + wp_string + comma_string + carrera
            flag = 1
            a = 1
        if "\t" in line:                        #checking for tabs return
            carrera = carrera + tab_string + comma_string + carrera
            flag = 1
        if '\n' not in line:
            carrera = carrera + mc_string + ne_string + carrera
            flag = 1
        if flag == 0:                           #checking if no error is true by setting flag equal to zero
            carrera = ne_string
        print('\t'.join(str(len(g)) for g in re.findall(r'\d+\.?(\d+)?', line )))
        print (carrera)
        baconFile.write('\t'.join(str(len(g)) for g in re.findall(r'\d+\.?(\d+)?', line ) ))
        baconFile.write(carrera + "\n")

with open("Version2_file.txt", 'r') as f:
    content = f.readlines()
    print('Number of Lines: {}'.format(len(content)))
    for i in range(len(content)):
            print('Numbers in Line {}: {}'.format(i+1, len(content[i].split(','))))
            baconFile.write('Number of lines: {}'.format(len(content)))
            baconFile.write('Numbers in Line {}: {}'.format(i+1, len(content[i].split(','))))  
baconFile.close()

预期写入输出文件:

Line 1: 1    2    3 Tab detected, whitespace detected
Line 2: 1    2    3 No error
Line 3: 1 Missing carriage return No error
Number of Lines: 3
Numbers in Line 1: 3
Numbers in Line 2: 3
Numbers in Line 3: 1

来自输出文件的实际:

Line 1:  1  3   2White Space Detected, tab detected, White Space Detected, 
Line 2:  1  3   2No Error
Line 3:  0Missing carriage returnNo Error
Number of lines: 3Numbers in Line 1: 3Number of lines: 3Numbers in Line 2: 3Numb

您已经在第一个open块中关闭了baconFile ,但不要在第二个open块中再次打开它。 此外,您永远不会在第二个open块中写入baconFile ,考虑到您没有在那里打开它,这是有道理的,但是您不能期望已经写入它。 看来您只是忘记添加一些write语句。 也许你混淆了writeprint 添加那些write语句,你应该是金。

baconFile = open(outfile,"wt")
with open("Version2_file.txt", 'r') as f:
    for line in f:                       
        # ... line processing ...
        baconFile.write(...)  # line format info here
    # baconFile.close()  ## <-- move this
with open("Version2_file.txt", 'r') as f:
    content = f.readlines()
    baconFile.write(...)  # number of lines info here
    for i in range(len(content)):
        baconFile.write(...)  # numbers in each line info here
baconFile.close()  # <-- over here

这是一个有用的技巧,您可以使用它使print语句将其输出发送到指定的文件而不是屏幕(即stdout ):

from contextlib import contextmanager
import os
import sys


@contextmanager
def redirect_stdout(target_file):
    save_stdout = sys.stdout
    sys.stdout = target_file
    yield
    sys.stdout = save_stdout

# Sample usage
with open('output2.txt', 'wt') as target_file:
    with redirect_stdout(target_file):
        print 'hello world'
        print 'testing', (1, 2, 3)

print 'done'  # Won't be redirected.

上面运行后output2.txt文件的内容:

hello world
testing (1, 2, 3)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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