我有从路径解压缩文件的代码。但是我不知道如何编写代码,以在已经存在的情况下跳过或删除带有解压缩文件的文件夹。 谢谢你的建议。
def unzip_file(self, path):
# Load file - function that reads a GTFS ZIP file.
#path = self.dockwidget.input_dir.filePath()
name = os.path.splitext(os.path.basename(path))[0]
# Create a folder for files.
path1 = os.path.join(os.path.dirname(path), name)
os.mkdir(path1)
# Extracts files to path.
with ZipFile(path, 'r') as zip:
# printing all the contents of the zip file
zip.printdir()
zip.extractall(path1)
# Select text files only.
print(path1)
print(path)
files = []
# r=root, d=directories, f = files
for r, d, f in os.walk(path1):
for file in f:
exten = os.path.splitext(os.path.basename(file))[1]
if exten == '.txt':
files.append(os.path.join(r, file))
return files
答案 0 :(得分:0)
检查os.path.exists(path)
的值并相应地设置逻辑。
https://docs.python.org/3.7/library/os.path.html#os.path.exists