Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/352.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python 3.6中将多行写入csv文件时面临的问题_Python_Csv - Fatal编程技术网

在python 3.6中将多行写入csv文件时面临的问题

在python 3.6中将多行写入csv文件时面临的问题,python,csv,Python,Csv,我的要求是读取目录中的所有文件,获得文件的长度和每个文件的字数,并将其作为一行存储在CSV文件中 下面是我的Python代码。 #遍历列表目录 for filename in os.listdir(passedArgument1): #Opening each file in the directory with open(passedArgument1+filename,"r",encoding="ISO-8859-1") as f: actualWordCount = 0

我的要求是读取目录中的所有文件,获得文件的长度和每个文件的字数,并将其作为一行存储在CSV文件中

下面是我的Python代码。 #遍历列表目录

 for filename in os.listdir(passedArgument1):
  #Opening each file in the directory
   with open(passedArgument1+filename,"r",encoding="ISO-8859-1") as f:
    actualWordCount = 0
  # Getting the file Size
    fileSize=os.path.getsize(passedArgument1+filename)
    for line in f:
  # Getting the word count
      actualWordCount+=writeToExcelFile(line)
  # Writing to a file 
      with open('output.csv', 'w') as csvfile:
       spamwriter = csv.writer(csvfile, delimiter=' ', quotechar='|',   quoting=csv.QUOTE_MINIMAL)
       spamwriter.writerow([actualWordCount,fileSize])

当我写入CSV文件时,它只写入最后一个文件的一条记录。我已经检查了writerows方法,但不确定它是如何工作的。如果能在Python 3.x中实现我的要求,我们将不胜感激。

您正在为每一行输出重新打开输出文件。只需打开一次。

您正在为每一行输出重新打开输出文件。只需打开一次。

试试这个

csvfile = open('output.csv', 'w')
# do your loop here and write/append to csvfile
csvfile.close()
试试这个

csvfile = open('output.csv', 'w')
# do your loop here and write/append to csvfile
csvfile.close()

我试图打开一次,将open方法放在顶部,但它给了我以下错误。ValueError:对关闭的文件执行I/O操作。@Sumanth:那么就不要关闭该文件。也许你的压痕是错的。您需要使用open在
中写入。如果使用open
,我会在检查您的建议后更新。我尝试过打开一次,将open方法放在顶部,但它给了我以下错误。ValueError:对关闭的文件执行I/O操作。@Sumanth:那么就不要关闭该文件。也许你的压痕是错的。您需要在
中使用open
进行编写。在我检查您的建议后,将立即进行更新explicit
close()
不是过去7-10年Python的最佳实践。OP已经将
一起使用,这是一种更可取的方法。在过去的7-10年中,显式
close()
不是Python中的最佳实践。OP已将
一起使用,这是更可取的。