【问题标题】:Python script works in command line, but not when running the .py filePython 脚本在命令行中有效,但在运行 .py 文件时无效
【发布时间】:2013-04-12 13:48:54
【问题描述】:

我显然还是个初学者,但我正在创建一个解析文件,它通过一个文本文件,并构建一个我需要的文件。

物流并不像明显发生的事情那么重要。

import fileinput;
for lines in fileinput.FileInput("c:/manhattan.txt", inplace=1):    
    lines = lines.strip();                      
    if lines == '': continue;
    print(lines);


source = open('c:/manhattan.txt','r');
hrt = open('c:/test.hrt','w');
currentline = str(source.readline());  
currentline.lstrip();
workingline = '';                      
while currentline[0] != " ":
    if currentline[0].isdigit() == True:
        if currentline[0:3] == workingline[0:3] and len(workingline)<160:  
            workingline = workingline + currentline[4:7];          
            currentline = str(source.readline());   
            currentline.lstrip();
        else:
            hrt.write(('\x01' + 'LOC01LOC' + workingline).ljust(401,' ') +'\n');  
            workingline = currentline[0:7].replace(';','E');
            currentline = str(source.readline());
            currentline.lstrip();
    else:
        currentline = str(source.readline());
        currentline.lstrip();

hrt.write(('\x01'+'LOC50US1   A*').ljust(401,' ' +'\n');                                                                                                                                                                                                                                                                                                                                                          
hrt.write(('\x02'+'LOCSUNSAT00:0023:5960 60             99990.00  0.00').ljust(401,' ')+'\n');                                                                                                                                                                                                                                                                                                                                                              
hrt.write(('\x02'+'US SUNSAT00:0023:5960 60             99990.03  0.03').ljust(401,' ') +'\n');  
hrt.close();
source.close();

它在 python 命令行中运行良好,但是在运行 .py 文件时它不会将最后三行写入文件。

有什么想法吗?

【问题讨论】:

  • 您遇到任何错误吗?
  • '其他链接\n' '讨论\n' '喜欢这个网站?我们通过 PayPal 接受捐款。\n' '' Traceback(最近一次调用最后一次):文件“”,第 1 行,在 IndexError: string index out of range >>> hrt.write(('\ x01'+'LOC50US1 A*').ljust(401,'') +'\n'); 402 >>> hrt.write(('\x02'+'LOCSUNSAT00:0023:5960 60 99990.00 0.00').lju st(401,'') +'\n'); 402 >>> hrt.write(('\x02'+'US SUNSAT00:0023:5960 60 99990.03 0.03').lju st(401,'') +'\n'); 402 >>> hrt.close(); >>> source.close(); >>>

标签: python python-3.x


【解决方案1】:

您是否尝试在关闭文件之前刷新缓冲区?

hrt.flush()

【讨论】:

  • 啊,我现在看到你在运行它时实际上遇到了一个错误。
  • 有一个错误,但是在python命令行中运行时仍然打印这3行,但在运行.py文件时没有。
猜你喜欢
  • 1970-01-01
  • 2013-02-07
  • 2021-11-13
  • 2017-03-26
  • 1970-01-01
  • 1970-01-01
  • 2012-01-31
  • 2018-05-29
  • 2017-01-15
相关资源
最近更新 更多