在python3.6中将多行写入csv文件时面临的问题

2024-09-28 03:19:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我的要求是读取目录中的所有文件,获得文件的长度,以及每个文件的字数,并将其作为一行存储在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方法,但不确定它是如何运行的有用。有吗感谢您帮助我在python3.x中实现我的要求


Tags: 文件csvthein目录forosas
1条回答
网友
1楼 · 发布于 2024-09-28 03:19:42

试试这个?你知道吗

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

相关问题 更多 >

    热门问题