简体   繁体   English

Python:将列表项写入文本文件

[英]Python: writing list items to text files

I'm writing the content from one column in a rather large Excel file into separate text files using xlrd , one text file for each row in the column. 我正在使用xlrd将相当大的Excel文件中一列的内容写入单独的文本文件,该列中的每一行都有一个文本文件。 In total, I have 1312 rows in the column, meaning I hope to get 1312 text files. 总的来说,我在该列中有1312行,这意味着我希望获得1312个文本文件。

This should be trivial. 这应该是微不足道的。 I manage just fine to save all the individual Excel cells from the colum into a Python list of 1312 items. 我可以很好地将列中的所有单个Excel单元格保存到包含1312个项目的Python列表中。 But for some reason when I run the code it only copies 619 out of 1312 list items into text files. 但是由于某种原因,当我运行代码时,它仅将1312个列表项中的619复制到文本文件中。 I don't get an error message, the code compiles successfully, it just refuses to create the remaining files. 我没有收到错误消息,代码成功编译,只是拒绝创建剩余文件。 It's also always 619 files that it creates, never more, never less. 它也始终创建619个文件,永远不会增加,永远不会减少。

Here is my code (The date is for naming the files after the date, which is another column in the Excel file. I made the datelist to check if it was perhaps not saving that part, but it is): 这是我的代码( date是用于在日期之后命名文件的日期,日期是Excel文件中的另一列。我制作了datelist以检查它是否未保存该部分,但确实如此):

import xlrd
import os

path = r'C:\Users\data'
file = "data.xlsx"

os.chdir(path)

book = xlrd.open_workbook(file)
sheet = book.sheet_by_index(0)
contentlist=[]
datelist=[]
for row in sheet.get_rows():
    date = str(row[5].value)
    datelist.append(date)
    content = str(row[7].value)
    contentlist.append(content)

    for item in datelist:
        filename = item + ".txt"
    for item in contentlist:
        with open(filename, 'w', encoding='utf-8') as f:
            f.write(str(item))

That code just looks completely wrong. 该代码看起来完全错误。

I guess what you mean is: 我想你的意思是:

for row in sheet.get_rows():
    name, content = str(row[5].value), str(row[7].value)
    with open(name + ".txt", 'w', encoding='utf-8') as f:
        f.write(content)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM