修改Excel/CSV中的所有值

o2rvlv0m  于 2022-12-06  发布在  其他
关注(0)|答案(5)|浏览(186)

我有一个问题,我不知道如何处理它。
我有一个Excel/CSV文件,我需要修改它。我需要添加引号到所有的单元格。
这是我的

Matter,TK,FeedT,Blank1,Blank2,Date,Time,Blank3,Blank4,Description

这就是我需要的

"Matter","TK","FeedT","Blank1","Blank2","Date","Time","Blank3","Blank4","Description"

有什么建议吗?

hzbexzde

hzbexzde1#

您可以使用csv模块。这也可以通过正确转义来处理带有换行符和嵌入式双引号的单元格。

import csv

# Note: Python 3.10+ required for this with syntax; otherwise, use two withs
with (open('input.csv', newline='') as fin,
      open('output.csv', 'w', newline='') as fout):

    reader = csv.reader(fin)
    writer = csv.writer(fout, quoting=csv.QUOTE_ALL)

    for line in reader:
        writer.writerow(line)

input.csv:

Matter,TK,FeedT,Blank1,Blank2,Date,Time,Blank3,Blank4,Description

output.csv

"Matter","TK","FeedT","Blank1","Blank2","Date","Time","Blank3","Blank4","Description"
a1o7rhls

a1o7rhls2#

请尝试以下操作:

cells = line.split(',')
line = ''
for cell in cells
    line = '"' + cell + '",'
if line[-1] == ','
    line = line[0:line.len() - 1]
hpcdzsge

hpcdzsge3#

如果您的目标是重写文件,那么这个解决方案将把您从阅读文件带到重写文件。

newFile = ""
with open('some.csv', "r") as csv_file:
    for row in csv_file:
        entries = row.split(",")
        result = list(map(lambda x: '"' + x + '"', entries))
        newFile += ",".join(result)
        newFile += "\n"
with open('some.csv', "w") as csv_file:
    csv_file.write(newFile)
3lxsmp7m

3lxsmp7m4#

如果你经常使用excel和python,那就熟悉一些Pandas的技巧,帮助你与excel交互。
1.复制excel文档的页眉:
1.在jupyter笔记本中运行python代码:

import pandas as pd

df = pd.read_clipboard()
df.columns = [f'"{col}"' for col in df.columns
df.to_clipboard(index=False)

1.将更新的列粘贴到excel文件中。

jv4diomz

jv4diomz5#

如果使用的是Excel文件,则可以按如下方式使用openpyxl模块:

import openpyxl as xl
filename = <*path-to-file*>
workbook = xl.load_workbook(filename)
ws = workbook.active
for i in range(ws.max_row):
    for j in range(ws.max_column):
        curr_value = ws.cell(row=i+1, column=j+1).value
        if curr_value == "None":
            continue
        new_value = f'"{curr_value}"'
        ws.cell(row=i+1, column=j+1).value = new_value

workbook.save(filename)

相关问题