简体   繁体   English

os.chdir 返回没有这样的文件或目录:'无'

[英]os.chdir returns No such file or directory: 'None'

How come that these lines of code creates a folder, but returns an error output?为什么这几行代码创建了一个文件夹,却返回错误output? It creates a folder, but doesnt recognize it when calling os.chdir(new_folder).它创建一个文件夹,但在调用 os.chdir(new_folder) 时无法识别它。

Updated更新

def Gibiru():
    id = request.args.get('ID') 
    key_ = id.split('*')[0] #lfc is the keyword
    output_dir = 'Images/Gibiru_pics'

    with open('URLS/Gibiru_urls.txt', 'r') as urls:
        for url in urls.readlines():
            url = url.rstrip("\n")
            download_url(url, output_dir, key_)

return str("Success")


def download_url(file_url, output_dir, key_):
    print("downloading: ",file_url)
    file_name_start_pos = file_url.rfind("/") + 1
    file_name = file_url[file_name_start_pos:]
    r = requests.get(file_url, stream=True)
    ts = time.time()
    file_path = os.path.realpath(__file__)
    output_files = file_path.replace('billede_indsamling.py',str(output_dir))
    os.chdir(output_files)
    new_folder = str(key_)+str(datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S'))
    #os.mkdir(new_folder) 
    os.makedirs(new_folder)
    os.chdir(new_folder)
    if r.status_code == requests.codes.ok:
        with open(file_name, 'wb') as f:
            for data in r:
                f.write(data)

The error I'm getting is我得到的错误是

 File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/os.py", line 225, in makedirs
    mkdir(name, mode)
FileExistsError: [Errno 17] File exists: 'lfc2022-07-25 21:41:55'

When exist_ok = True is applied it creates a folder instead of going inside the folder and working.应用exist_ok = True 时,它​​会创建一个文件夹,而不是进入文件夹并工作。

输出

os.makedirs() doesn't return the name of the directory it created. os.makedirs()不返回它创建的目录的名称。 Assign the directory name to a variable first, and use that in both function calls.首先将目录名称分配给一个变量,然后在 function 调用中使用它。

key_ = "Test"
new_folder = str(key_)+str(datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M'))
os.makedirs(new_folder, exist_ok=True)
os.chdir(new_folder)

This seems to be the solution:这似乎是解决方案:

file_path = os.path.realpath(__file__)
output_files = file_path.replace('billede_indsamling.py',str(output_dir))
os.chdir(output_files)
new_folder = str(key_)+str(datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d'))
#os.mkdir(new_folder) 
path = os.path.join(output_files, new_folder)

if not os.path.exists(path):
    os.makedirs(path)
    print("Directory '%s' created successfully" %new_folder)
elif os.path.exists(path):
    os.chdir(path)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM