在python 3.6中将多行写入csv文件时面临的问题
我的要求是读取目录中的所有文件,获得文件的长度和每个文件的字数,并将其作为一行存储在CSV文件中 下面是我的Python代码。 #遍历列表目录在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
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
进行编写。在我检查您的建议后,将立即进行更新explicitclose()
不是过去7-10年Python的最佳实践。OP已经将与
一起使用,这是一种更可取的方法。在过去的7-10年中,显式close()
不是Python中的最佳实践。OP已将与
一起使用,这是更可取的。