我是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