简体   繁体   English

在 Python 中创建二进制只读文件时出现 FileNotFoundError

[英]FileNotFoundError when creating a binary read only file in Python

I'm creating an FTP client and am attempting to download from and upload files to an FTP server.我正在创建一个 FTP 客户端,并尝试从 FTP 服务器下载和上传文件。

Downloading the files work fine as I have no issues creating a write only binary file , that does not initially exist on my local computer:下载文件工作正常,因为我在创建只写二进制文件时没有问题,该文件最初不存在于我的本地计算机上:

if cmnd1[0] == 'get':
    f1 = open('newDownloadText.txt', 'wb')
    ftp_cl.retrbinary("RETR " + cmnd1[1], f1.write, 1024)
    f1.close()
    ftp_cl.quit()
    break

However, I am unable to upload files to the server as I cannot successfully create a new read only binary file :但是,我无法将文件上传到服务器,因为我无法成功创建新的只读二进制文件

elif cmnd1[0] == 'put':
    f2 = open('newUploadTest.txt', 'rb')
    ftp_cl.storbinary("STOR " + cmnd1[1], f2)
    f2.close()
    ftp_cl.quit()
    break

My code fails when I attempt to create 'newUploadTest.txt'当我尝试创建“newUploadTest.txt”时我的代码失败

Traceback (most recent call last):
  File "client.py", line 29, in <module>
    f2 = open('newUploadTest.txt', 'rb')
FileNotFoundError: [Errno 2] No such file or directory: 'newUploadTest.txt'

I have seen other posts on stackoverflow with individuals creating a new read only binary files without issues using 'rb' as a parameter, not sure why mine fails every time.我在 stackoverflow 上看过其他帖子,其中有人使用“rb”作为参数创建了一个新的只读二进制文件而没有出现问题,不确定为什么我的每次都失败。

Code:代码:

  • File must be created before reading, whereas write mode creates the file.文件必须在读取之前创建,而写入模式创建文件。

creating a new read only binary files创建一个新的只读二进制文件

  • 'rb' mode does not Create read only binary , but it reads a binary file which already exists. 'rb'模式不会创建只读二进制文件,但它会读取一个已经存在的二进制文件。
  • 'rb' mode opens a binary file which already exists in a read only mode. 'rb'模式打开一个已经以只读模式存在的二进制文件。 It is not creating any file.它没有创建任何文件。
from os.path import isfile
if my_condition:
    file = 'newUploadTest.txt'
    # Check if the file exists
    if isfile(file):
        # open binary file
        f2 = open(file, 'rb')
        # do something...
        f2.close()
    else:
        print("File doesn't exists")

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

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