读取一个excel文件,为每一行创建一个txt文件。我正在使用的代码只为excel表的最后一行创建一个文本文件

时间:2017-07-30 18:32:12

标签: python excel file xlrd

我是一个初学者,使用app sololearn完成了python理论,但直到现在才开始使用我自己的编码。我也在这里搜索并找到了一些有希望的答案,但并不完全符合我的需求。所以我希望得到你们的一些意见。

这是我想做的事情: 我在第一列中有一个带有Artist Name的表文件(excel),第二列中有Album Name,第三列中有一个关于此Album的Web链接。 我希望python使用第三列的Web链接为每一行创建一个txt文件。相关的txt文件应使用第一列中的Artist Name和第二列中的Album name作为新创建的txt文件的名称,在艺术家名称和相册名称之间使用“ - ”。

Harald Nordgren非常友好地为我编写了以下代码:

import xlrd

def replace_with_underscores(cell):
return cell.value.replace(" ", "_")

wb = xlrd.open_workbook("input-file.xlsx")
sh = wb.sheet_by_index(0)

for row in sh.get_rows():
    artist = replace_with_underscores(row[0])
    album = replace_with_underscores(row[1])
    link = row[2].value

filename = artist + "-" + album + ".txt"
with open(filename, 'w') as f:
    f.write(link)

将此代码应用于我的excel表只会创建一个新的txt文件,其值为表的最后一行。 我真的希望有人能在这段代码中找到错误。

非常感谢Harald Nordgren为我编写上述代码。

1 个答案:

答案 0 :(得分:1)

import xlrd

def replace_with_underscores(cell):
    return cell.value.replace(" ", "_")

wb = xlrd.open_workbook("input-file.xlsx")
sh = wb.sheet_by_index(0)

for row in sh.get_rows():
    artist = replace_with_underscores(row[0])
    album = replace_with_underscores(row[1])
    link = row[2].value

    filename = artist + "-" + album + ".txt"
    with open(filename, 'w') as f:
        f.write(link)