无法写入" w" mode(IOError:[Errno 2]没有这样的文件或目录:' items.csv')

时间:2014-03-19 14:52:52

标签: python

我有一个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")。但是再次遇到同样的错误

EDIT2:调用脚本:

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 :(得分:1)

这里的主要问题是,由于您正在Python 2.7中使用子进程来定向其他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”权限按顺序附加到每个进程的文件中。

还请注意,直到关闭文件,才会将来自进程的数据流实际写入文件。

答案 1 :(得分:0)

您尝试打开文件'%s/items.csv',然后将% path应用于open()的*返回值。

将字符串格式移动到字符串:

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

但是,您应该使用os.path library来处理路径操作:

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

或者,在这种情况下,请使用os.path.abspath,因为它会为您使用os.getcwd()作为相对路径:

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