在函数中传递相对路径
有人能告诉我下面这个函数声明是不是正确的方式来给一个函数传递相对路径吗?这个调用只传了一个变量。当我加上第二个变量(绝对路径)时,我的函数就不工作了。
def extract(tar_url, extract_path='.'):
这个调用不工作:
extract(chosen, path)
这个可以工作,但没有提取:
extract(chosen)
完整代码:
def do_fileExtract(self, line):
defaultFolder = "Extracted"
if not defaultFolder.endswith(':') and not os.path.exists('c:\\Extracted'):
os.mkdir('c:\\Extracted')
raw_input("PLACE .tgz FILES in c:\Extracted AT THIS TIME!!! PRESS ENTER WHEN FINISHED!")
else:
pass
def extract(tar_url, extract_path='.'):
print tar_url
tar = tarfile.open(tar_url, 'r')
for item in tar:
tar.extract(item, extract_path)
if item.name.find(".tgz") != -1 or item.name.find(".tar") != -1:
extract(item.name, "./" + item.name[:item.name.rfind('/')])
userpath = "Extracted"
directory = os.path.join("c:\\", userpath)
os.chdir(directory)
path=os.getcwd() #Set log path here
dirlist=os.listdir(path)
files = [fname for fname in os.listdir(path)
if fname.endswith(('.tgz','.tar'))]
for item in enumerate(files):
print "%d- %s" % item
try:
idx = int(raw_input("\nEnter the file's number:\n"))
except ValueError:
print "You fail at typing numbers."
try:
chosen = files[idx]
except IndexError:
print "Try a number in range next time."
newDir = raw_input('\nEnter a name to create a folder a the c: root directory:\n')
selectDir = os.path.join("c:\\", newDir)
path=os.path.abspath(selectDir)
if not newDir.endswith(':') and not os.path.exists(selectDir):
os.mkdir(selectDir)
try:
extract(chosen, path)
print 'Done'
except:
name = os.path.basename(sys.argv[0])
print chosen
1 个回答
1
看起来你在 "PLACE .tgz FILES in c:\Extracted AT THIS TIME!!! PRESS ENTER WHEN FINISHED!"
这段话里漏掉了一个转义字符。我觉得 raw_input 只把提示字符串当作普通字符串来看,而不是原始字符串,实际上它只关注用户输入的内容。不过,这应该不会影响你程序的功能。
你是在 Unix 系统上还是 Windows 系统上?我原以为在 Unix 系统上,你应该用 /
这个斜杠作为分隔符,而不是 \\
这个反斜杠。
我在这个文件上测试了一些代码:http://simkin.asu.edu/geowall/mars/merpano0.tar.gz
以下这段代码:
>>> from os import chdir
>>> import tarfile
>>> chdir(r'C:\Users\Acer\Downloads')
>>> tar_url = 'merpano0.tar.gz'
>>> print tar_url
merpano0.tar.gz
>>> tar = tarfile.open(tar_url, 'r')
>>> extract_path = 'C:\\Users\\Acer\\Downloads\\test\\'
>>> for item in tar:
tar.extract(item, extract_path)
在我这边运行得很顺利,没有任何问题。在 test
目录下,我得到了一个文件夹,里面有一些文件,和原始的 tar 文件完全一样。你能解释一下你的代码中有什么不同的地方可能导致问题吗?