用python在Ubuntu中创建目录

2024-03-28 22:43:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用python在Ubuntu中创建目录,并在其中保存zip文件。我的代码在windows下运行得很好,但是在ubuntu中运行得很奇怪。在

import os
import zipfile
import datetime
from os.path import expanduser


home = expanduser('~')
zip_folder = home + '\\Documents\\ziprep'  # enter folder path where files are
zip_path = home + '\\Documents\\zips'        #enter path for zip to be saved

global fantasy_zip

def dailyfiles(weekly_file,today):
    today = str(today)
    try:
        os.mkdir(zip_path + today)
    except OSError:
        print("Creation of the directory %s failed" % today)
    else:
        print("Successfully created the directory %s " % today)
    for folder, subfolders, files in os.walk(zip_folder):
        for file in files:
            if file.startswith(today) and not file.endswith('.zip') and file not in weekly_file:
                print("Zipping  - Filename " + file)
                zip_in = zip_path + today + "\\"
                fantasy_zip = zipfile.ZipFile(zip_in + file + '.zip', 'w')
                fantasy_zip.write(os.path.join(folder, file),
                                  os.path.relpath(os.path.join(folder, file), zip_folder),
                                  compress_type=zipfile.ZIP_DEFLATED)

        fantasy_zip.close()



def main():
    weekday = str(datetime.datetime.today().weekday())
    today = datetime.date.today().strftime('%Y%m%d')
    dailyfiles(weekly_file,today)

if __name__ == '__main__':
    main()

从逻辑上讲,它应该在指定的路径上创建一个包含今天日期的文件夹。但是它在ubuntu中创建了一个文件夹,整个路径在m script所在的同一个目录下。在

例如,它正在创建名为“/home/downloads/scripypath”的文件夹

而我需要'20191106'在脚本中指定的路径。该代码在windows下运行良好。在

{a1到当前链接}


Tags: pathinimporthomefortodaydatetimeos
2条回答

我建议在第8行和第9行分别使用home + '/Documents/ziprep/'和{}。在

编辑:对不起,忘了为什么这应该解决问题。在Linux或Unix中,目录使用“/”而不是“\”(在Windows中使用)作为目录分隔符。在

in ubuntu directory structure is totally different and they use \ instead of /. so prepare your link as ubuntu file structure.

相关问题 更多 >