繁体   English   中英

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

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

我正在创建一个 FTP 客户端,并尝试从 FTP 服务器下载和上传文件。

下载文件工作正常,因为我在创建只写二进制文件时没有问题,该文件最初不存在于我的本地计算机上:

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

但是,我无法将文件上传到服务器,因为我无法成功创建新的只读二进制文件

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

当我尝试创建“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'

我在 stackoverflow 上看过其他帖子,其中有人使用“rb”作为参数创建了一个新的只读二进制文件而没有出现问题,不确定为什么我的每次都失败。

代码:

  • 文件必须在读取之前创建,而写入模式创建文件。

创建一个新的只读二进制文件

  • 'rb'模式不会创建只读二进制文件,但它会读取一个已经存在的二进制文件。
  • 'rb'模式打开一个已经以只读模式存在的二进制文件。 它没有创建任何文件。
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