Python 如何分割csv单元格中的数据并创建新行
我是Python的新手。我已经搜索了数据库,没有找到我问题的确切答案。这是我的基本问题: 我有一个csv文件,格式如下:Python 如何分割csv单元格中的数据并创建新行,python,arrays,csv,dictionary,split,Python,Arrays,Csv,Dictionary,Split,我是Python的新手。我已经搜索了数据库,没有找到我问题的确切答案。这是我的基本问题: 我有一个csv文件,格式如下: Header1, Header2, Header3 1, a, DF FD 2, b, DD FD 我需要以csv形式以以下形式写出: Header1, Header2, Header3 1, a, DF 1, a, FD 2, b, DD 2, b, FD 现在我带着我的代码来到这里: 我用打印只是为了看看我有什么。我现在的问题
Header1, Header2, Header3
1, a, DF FD
2, b, DD FD
我需要以csv形式以以下形式写出:
Header1, Header2, Header3
1, a, DF
1, a, FD
2, b, DD
2, b, FD
现在我带着我的代码来到这里:
我用打印只是为了看看我有什么。我现在的问题是如何分割第三列中的空格分隔值,并获得我试图实现的输出?我的实际文件更复杂,但我认为对此的回答将使我朝着正确的方向前进。我认为以下内容就是你的意思:
import csv
import sys
# Index (starts at 0) of the column that needs to be split up
splitColIndex = 2
with open('InputFile.csv') as f:
reader = csv.reader(f, delimiter = ',')
for row in reader:
# Get the element that needs splitting
splitElem = row[splitColIndex]
for subElem in splitElem.split():
# Iterate over the row elements
# (actually the indices)
for idx in range(len(row)):
# If the column doesn't need splitting, we
# can just copy it, otherwise we need to use
# one of the split up values
if idx != splitColIndex:
elem = row[idx]
else:
elem = subElem
if idx > 0:
sys.stdout.write(",")
sys.stdout.write(elem)
sys.stdout.write("\n")
在这里,我使用
split
函数将例如的“DF-FD”
转换为一个列表[“DF”,“FD”]
。我还使用了sys.stdout.write
而不是print
来稍微控制输出的格式。通过“需要读取”,您的意思是需要生成适当行以供进一步处理的内容,还是要写出新的csv文件?是,对不起,我写的方式很混乱,谢谢你的输入!我正在自学python,事情进展缓慢。我试图将此应用于我的文件(该文件在需要拆分的列之后有两列),但无法确定如何使其工作。你有什么建议吗?好的,我明白了,我对代码做了一些修改,这样你就可以指出需要拆分哪个特定列了。太棒了!谢谢你的评论。这确实有助于获得for循环嵌套。我能够调整代码,使其适合我的输入文件。它以我想要的方式印在外壳上(对吗?)。现在我需要写入一个.csv文件而不是shell。我在想csv.writer()?重定向输出不是更容易吗?例如,“python myprogram.py>newoutput.csv”(不带引号)
import csv
import sys
# Index (starts at 0) of the column that needs to be split up
splitColIndex = 2
with open('InputFile.csv') as f:
reader = csv.reader(f, delimiter = ',')
for row in reader:
# Get the element that needs splitting
splitElem = row[splitColIndex]
for subElem in splitElem.split():
# Iterate over the row elements
# (actually the indices)
for idx in range(len(row)):
# If the column doesn't need splitting, we
# can just copy it, otherwise we need to use
# one of the split up values
if idx != splitColIndex:
elem = row[idx]
else:
elem = subElem
if idx > 0:
sys.stdout.write(",")
sys.stdout.write(elem)
sys.stdout.write("\n")