【发布时间】:2023-04-08 01:00:02
【问题描述】:
我是 Python 新手,我正在处理一些 tar 文件。以下示例有效:
#!/usr/bin/python
import os, readline, tarfile, scipy.io, numpy as np, sys
year = 2012;
month = 12;
day = 10;
RS = 9;
hour = 00;
minute = 05;
seconds = 00;
UTC = 1355094300;
anArchive = '/Users/user/data/20121210.zip';
tar = tarfile.open(anArchive);
dynamicPath = './%4d%2d%2d/RS%02d/%02d%02d%02d_%10d/all.txt' %(year, month, day, RS, hour,minute, seconds, UTC);
print(dynamicPath);
memb = tar.getmember(dynamicPath);
file = tar.extractfile(memb.name);
print('loading file with measurements...\n');
contents = file.read();
destinationFile = open("extractedFile.txt", "w");
destinationFile.write(contents);
从 tar 中获取文件,解压缩并将其写入新文件。
现在我想定义一个做同样事情的函数:
#!/usr/bin/python
import os, readline, tarfile, scipy.io, numpy as np, sys
def extractFile():
year = 2012;
month = 12;
day = 10;
RS = 9;
hour = 00;
minute = 05;
seconds = 00;
UTC = 1355094300;
anArchive = "/Users/user/data/20121210.zip";
tar = tarfile.open(anArchive);
dynamicPath = "./%4d%2d%2d/LOSS_RS%02d/%02d%02d%02d_%10d/all.txt" %(year, month, day, RS, hour,minute, seconds, UTC);
print(dynamicPath);
#memb = tar.getmember("./20121210/RS09/004501_1355096701/all.txt");
memb = tar.getmember(dynamicPath);
file = tar.extractfile(memb.name);
print('loading file with measurements...\n');
contents = file.read();
destinationFile = open("extractedFile.txt", "w");
destinationFile.write(contents);
return
在我保存它并确保它是可执行的之后,我从终端执行它,同时检查缩进错误:
python -t extractFile.py
结果什么都没有。没有错误,执行“完成”但没有结果,就像我执行了空代码一样。
任何想法为什么相同的代码在用作函数时不起作用?
【问题讨论】:
-
你必须实际调用函数:
extractFile()
-
您可能需要考虑
if __name__ == '__main__':
extractFile()
。这意味着您可以在导入此模块的其他程序中使用extractFile
,也可以将其用作脚本。但是,如果您不需要它,则不必了解它……
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:输入函数时Python代码不起作用 - Python技术站