【问题标题】:Write a new folder in current directory and write file to it在当前目录中写入一个新文件夹并将文件写入其中
【发布时间】:2018-05-25 10:08:57
【问题描述】:

我有以下脚本将输入文件写入新目录。我想更改它,这样我就不必明确告诉它在哪个目录中写入新目录。这种当前方法工作​​正常,但需要用户输入路径。我看到了以下New folder that is created inside the current directory,并通过以下方式修改了我的脚本

import os

if not os.path.isdir('/home/bkwx97/python/test3/MINP'):
    os.mkdir('/home/bkwx97/python/test3/MINP')


with open('/home/bkwx97/python/test3/MINP/MINP','w') as f:

得到了错误

“文件“test3backupdir2.py”,第 8 行,在 with open('final_directory/MINP.txt','w') as f: FileNotFoundError: [Errno 2] No such file or directory: 'final_directory/MINP.txt'"

我错过了一些简单的东西吗?或者我可以不改变它,所以它会在当前目录中写入一个新文件夹,并在那里写入输入?

import os,os.path

current_directory = os.getcwd()
final_directory = os.path.join(current_directory,r'MINP')
if not os.path.exists(final_directory):
   os.makedirs(final_directory)

with open('final_directory/MINP.txt','w') as f:

【问题讨论】:

  • 错字:with open('final_directory/MINP.txt','w') as f: 应该是with open(os.path.join(final_directory,'MINP.txt'),'w') as f
  • 您似乎将名为 final_directory 的变量与文字字符串 'final_directory' 混淆了。如果你有一个名为foo 的变量,你不能只写'foo/bar.txt' 并扩展变量的值。
  • 您的工作目录是否与所需的输入目录相同?您是否从同一根目录中调用脚本?
  • @albert 我确实从同一个根目录中调用脚本。
  • @bkw:请将脚本和所有其他需要的文件复制到它自己的目录中,并提供完整的目录结构和代码sn-p。

标签: python python-3.x


【解决方案1】:

也许您正在寻找的是:

with open('{}/MINP.txt'.format(final_directory),'w') as f:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-11
    • 1970-01-01
    • 1970-01-01
    • 2013-03-13
    相关资源
    最近更新 更多