将列表项写入CSV时删除引号

2024-09-28 22:22:49 发布

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

我试图做的是在将数据写入新的CSV文件时删除引号

我尝试过使用s.splits和.replaces,但运气不佳。你们能给我指一下正确的方向吗

当前代码:

def createParam():
    with open('testcsv.csv', 'r') as f:
        reader = csv.reader(f)
        csvList = list(reader)

    for item in csvList:
        os.mkdir(r"C:\Users\jefhill\Desktop\Test Path\\" + item[0])
        with open(r"C:\Users\jefhill\Desktop\Test Path\\" + item[0] + r"\prm.263", "w+") as f:
            csv.writer(f).writerow(item[1:])
        f.close

testcsv.csv中的数据:

0116,"139,data1"
0123,"139,data2"
0130,"35,data678"

运行脚本时的数据输出(在每个文件中):

"139,data1"
"139,data2"
"35,data678"

我想要的数据:

139,data1
139,data2
35,data678

Tags: 文件csv数据aswithopenitemusers
1条回答
网友
1楼 · 发布于 2024-09-28 22:22:49

您可以使用str.replace将“(双引号)替换为“”(null)。 然后split打印列表中除第一项以外的所有项目。

with open('outputfile.csv', w) as outfile:       # open the result file to be written
    with open('testcsv.csv', 'r') as infile:     # open the input file
        for line in infile:                      # iterate through each line in input file
            newline = line.replace('"', '')      # replace double quotes with no space
            outfile.write(newline.split(',',maxsplit=1)[1])  # write second element to output file after splitting the newline once

使用with open...时不需要f.close()

相关问题 更多 >