无法在“w”模式下写入文件(IOError: [Errno 2] 没有该文件或目录: 'items.csv')

1 投票
2 回答
634 浏览
提问于 2025-04-17 22:59

我有一个Python脚本,它通过subprocess调用了一些其他的Python脚本。其中一个脚本有这么一行:

items = open("items.csv","w")

我还尝试过:

path = os.getcwd()
items = open("%s/items.csv","w") %path

但是这给了我以下错误:

IOError: [Errno 2] No such file or directory: 'items.csv'

如果我用“w”模式打开文件,它应该在不存在的时候被创建。那么为什么我会收到这个错误呢?

谢谢

编辑:我还尝试使用items = open("%s/items.csv" % path,"w")。但是又出现了同样的错误。

编辑2:调用这个脚本的是:

import subprocess
import sys
import shlex
import fileinput
import os

cmd = "python2 convert.py ebay.csv ebay.xml"
arg = shlex.split(cmd)
p = subprocess.Popen(arg)
p.wait()

cmd1 = "python2 convert.py all_products.csv all_products.xml"
arg1 = shlex.split(cmd1)
p1 = subprocess.Popen(arg1)
p1.wait()

ebay = open("ebay.xml")
voylla = open("all_products.xml")

for line in fileinput.input("ebay.xml", inplace=True):
    print(line.replace("&", "and"))

for line in fileinput.input("all_products.xml", inplace=True):
    print(line.replace("&", "and"))

path = os.getcwd()
print path
cmd2 = "python2 compare.py ebay.xml all_products.xml"
arg2 = shlex.split(cmd2)
print cmd2
p2 = subprocess.Popen(arg2)
p2.wait()

cmd4 = "python2 convert.py items.csv items.xml"
arg4 = shlex.split(cmd4)
p4 = subprocess.Popen(arg4)
p4.wait()

#cmd4 = "python2 ReviseItem.py"
#arg4 = shlex.split(cmd4)
#p4 = subprocess.Popen(arg4)
#p4.wait()

compare.py:

from xml.dom.minidom import parse, parseString
import xml.etree.ElementTree as ET
import sys
import os

#sys.stdout = open('file', 'w')
ebay = sys.argv[1]
voylla = sys.argv[2]

tree = ET.parse(ebay)
root = tree.getroot()

tree1 = ET.parse(voylla)
root1 = tree1.getroot()

path = os.getcwd()

items = open("%s/items.csv" % path,"w")

2 个回答

0

你尝试打开一个文件 '%s/items.csv',然后把 % path 应用到 open() 的返回值上。

把字符串格式化的部分移动到字符串里面:

items = open("%s/items.csv" % path, "w")

不过,你应该使用 os.path 来处理路径的问题:

items = open(os.path.join(path, 'items.csv'), 'w')

或者,在这种情况下,使用 os.path.abspath,因为它会为你自动使用 os.getcwd() 来处理相对路径:

items = open(os.path.abspath('items.csv'), 'w')
1

这里主要的问题是,你在使用Python 2.7的subprocess模块来控制其他Python进程时,文件会被第一个尝试创建和写入文件的进程锁定。根据文档的说明:

Popen.wait()
Wait for child process to terminate. Set and return returncode attribute.

Warning This will deadlock when using stdout=PIPE and/or stderr=PIPE and the child process 
generates enough output to a pipe such that it blocks waiting for the OS pipe buffer to 
accept more data. Use communicate() to avoid that.

还有一个需要注意的问题是,你在使用open时用的是“w”权限,这意味着之前的所有内容都会被覆盖。更好的做法是先在一个主进程中打开文件,创建并关闭它,然后在每个进程中使用“a”权限来追加内容。

另外要注意的是,进程的数据流在文件关闭之前其实并不会写入到文件中。

撰写回答