简体   繁体   English

以“w+”模式打开文件:FileNotFoundError: [Errno 2] No such file or directory

[英]open file in "w+" mode: FileNotFoundError: [Errno 2] No such file or directory

python beginner here. python 初学者在这里。 Using mac.使用麦克。

I'm creating a program that saves internet speed tests into a.csv file (appends to existing file, or writes new file if it doesn't exist)我正在创建一个程序,将互联网速度测试保存到 a.csv 文件中(附加到现有文件,如果不存在则写入新文件)

I got this to work with the following:我得到这个与以下工作:

if exists('internetspeedtimes.csv'):
  with open('internetspeedtimes.csv', 'a+') as f:
    f.seek(0, 0)
    a = f.read()
    f.write('\n')
    f.write(data)
else:
  with open('internetspeedtimes.csv', 'w+') as f:
    f.write(data)

I now want to take this a step further to create a new file each day:我现在想更进一步,每天创建一个新文件:

filename = 'InternetSpeedTest_' + now.strftime("%D") + '.csv'

I then use filename instead of 'internetspeedtimes.csv' :然后我使用filename而不是'internetspeedtimes.csv'

filename = 'InternetSpeedTest_' + now.strftime("%D") + '.csv'
if exists(filename):
    with open(filename, 'a+') as f:
        f.seek(0, 0)
        a = f.read()
        f.write('\n')
        f.write(data)
else:
    with open(filename, 'w+') as f:
        f.write(data)

I get the following error corresponding to the else statement (the 'w+' line):我收到与else语句( 'w+'行)相对应的以下错误:

FileNotFoundError: [Errno 2] No such file or directory: 'InternetSpeedTest_11/24/21.csv'

I've tried:我试过了:

  • Most answers to this question seem to be an issue of directory.这个问题的大多数答案似乎都是目录问题。 However, I also specifying the exact directory:但是,我还指定了确切的目录:

    filename = '/Users/me/PycharmProjects/pythonProject2/venv' + now.strftime("%D") + '.csv'文件名 = '/Users/me/PycharmProjects/pythonProject2/venv' + now.strftime("%D") + '.csv'

Which didn't work.这没有用。 I'm confused because I can get an appropriate answer when feeding a str into open(), but not when feeding an object that is of class str (ie filename).我很困惑,因为在将 str 输入 open() 时可以获得适当的答案,但在输入 class str (即文件名)的 object 时却不能。

Thank you very much!非常感谢!

Your filename is being treated as several subdirectories then a file, namely您的文件名被视为几个子目录,然后是一个文件,即

InternetSpeetTest_11/
  24/
    21.csv

Therefore the "No such file or directory" error is telling you those intermediate directories do not exist.因此,“没有这样的文件或目录”错误告诉您那些中间目录不存在。 Instead switch to something that doesn't look like a directory such as而是切换到看起来不像目录的东西,例如

'InternetSpeedTest_11-24-21.csv'

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

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