IOError: [Errno 2] No such file or directory trying to open a file

前端 未结 5 1435
無奈伤痛
無奈伤痛 2020-11-28 10:15

I am very new to Python so please forgive the following basic code and problem, but I have been trying to figure out what is causing the error I am getting (I have even look

5条回答
  •  独厮守ぢ
    2020-11-28 10:34

    Even though @Ignacio gave you a straightforward solution, I thought I might add an answer that gives you some more details about the issues with your code...

    # You are not saving this result into a variable to reuse
    os.path.join(src_dir, f)
    # Should be
    src_path = os.path.join(src_dir, f)
    
    # you open the file but you dont again use a variable to reference
    with open(f)
    # should be
    with open(src_path) as fh
    
    # this is actually just looping over each character 
    # in each result of your os.listdir
    for line in f
    # you should loop over lines in the open file handle
    for line in fh
    
    # write? Is this a method you wrote because its not a python builtin function
    write(line)
    # write to the file
    fh.write(line)
    

提交回复
热议问题