我是Python新手,我正在处理一些tar文件。下面的示例工作:Python代码在进入函数时不起作用
#!/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()' – mdurant 2014-09-24 19:01:04
你可能要考虑'如果__name__ == '__main __':''extractFile()'。这意味着您可以在导入此模块的其他程序中使用'extractFile',并将其用作脚本。但是,如果你不需要这个,你不需要了解它... – abarnert 2014-09-24 19:04:35