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

时间:2019-07-02 23:29:05

标签: python python-2.7

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

我试图在for循环之外添加另一个for循环。我尝试将其放入for循环中,这很复杂。

文本文件编号列表:

::@ECHO OFF
@For /F Delims^=^= %%Z In ('Set Disk 2^>Nul') Do @Set "%%Z="
@For /F Delims^= %%V In ('WMIC DiskDrive Assoc /AssocClass:Win32_DiskDriveToDiskPartition 2^>NUL^|Find /I "Disk #"') Do (
    @For /F Tokens^=2Delims^=^" %%W In ("%%V") Do (
        @For /F Tokens^=2^,4Delims^=^" %%X In ('WMIC Path Win32_LogicalDiskToPartition 2^>NUL^|Find "%%W" 2^>Nul') Do (
            @For /F "Tokens=2Delims=#," %%Z In ("%%X") Do (
                @If Defined Disk%%Z (
                    Call Set "Disk%%Z=%%Disk%%Z%% %%Y"
                ) Else (
                    Set "Disk%%Z=%%Y"
                )
            )
        )
    )
)
@Set Disk 2>NUL
Pause

代码:

runtime: python27
threadsafe: true

skip_files:
- ^(?!dist)

handlers:
- url: /en/(.*\.(gif|png|jpg|css|js)(|\.map))$
  static_files: dist/en/\1
  upload: dist/en/(.*)(|\.map)

- url: /it/(.*\.(gif|png|jpg|css|js)(|\.map))$
  static_files: dist/it/\1
  upload: dist/it/(.*)(|\.map)

- url: /en/(.*)
  static_files: dist/en/index.html
  upload: dist/en/index.html

- url: /it/(.*)
  static_files: dist/it/index.html
  upload: dist/it/index.html

- url: /
  static_files: dist/en/index.html
  upload: dist/en/index.html

error_handlers:
- file: index.html

预期写入输出文件:

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

2 个答案:

答案 0 :(得分:1)

您已经在第一个baconFile块中关闭了open,但是在第二个open块中没有再次打开它。此外,您永远不会在第二个baconFile块中写入open,考虑到您尚未在其中打开它,这是有道理的,但是您就无法期望对其进行写入。看来您只是忘了添加一些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

答案 1 :(得分:0)

这是一个有用的技巧,可用于使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)