with open('APEC.html', newline='', encoding='utf-8') as f:
reader = csv.reader(f)
for row in reader:
pass
with open('APEC.html') as f:
Model = [row for row in f if row.startswith('A')]
with open('APEC.html') as f:
Pad_Shoe = [row for row in f if row.startswith('P')]
with open('APEC.html') as f:
Kit_Lead = [row for row in f if row.startswith('K')]
with open('APEC.html') as f:
Disc_Drum = [row for row in f if row.startswith('D')]
with open('APEC.html') as f:
Year = [row for row in f if row.startswith('0')]
with open('APEC.html') as f:
C1top = [row for row in f if row.startswith('Model')]
with open('APEC.html') as f:
C2top = [row for row in f if row.startswith('Year')]
with open('APEC.html') as f:
C3top = [row for row in f if row.startswith('Pad / Shoe')]
with open('APEC.html') as f:
C4top = [row for row in f if row.startswith('Kit / Lead')]
with open('APEC.html') as f:
C5top = [row for row in f if row.startswith('Disc / Drum')]
with open('APEC.html') as f:
C6top = [row for row in f if row.startswith('Adj Bar')]
c1 = (C1top, Model)
c2 = (C2top, Year)
c3 = (C3top, Pad_Shoe)
c4 = (C4top, Kit_Lead)
c5 = (C5top, Disc_Drum)
c6 = (C3top, Pad_Shoe)
c7 = (C4top)
c8 = (C6top)
c9 = (C5top, Disc_Drum)
for nth, (c1, c2, c3, c4, c5, c6, c7, c8, c9) in enumerate(zip(c1, c2, c3, c4, c5, c6, c7, c8, c9)):
pass
file = open("Table.csv", "w")
for items in c1:
file.write([items,])
打开包含我需要的数据的Html文件
从html文件中提取数据并搜索以' x'开头的每一行。
设置变量
将他们全部拉到一起
打开文件并尝试添加上面的项目
任何人告诉我哪里出错或告诉我如何将上述所有变量添加到CSV文件中(列不是行)
语法:
Traceback (most recent call last): File
"C:\Users\B8\Desktop\Task\writing_to_columns.py", line 67, in <module>
file.write([items,]) TypeError: must be str, not list
答案 0 :(得分:0)
您似乎受到了许多误解(例如,您可以将包含HTML的文件视为包含CSV数据),但最直接解决您问题的问题是您可以编写CSV文件的概念列而不是行。
CSV文件不是本质上是柱状的,尽管它们通常以有限的方式使用(每行中具有相同数量的项目),这相对容易被解释为列。 CSV文件按顺序写入,换行符分隔的值集合,逗号分隔每个值,每个值可选地用引号括起来(通常是ASCII双引号字符)。
CSV中没有要求每行具有相同数量的值。
如果没有先读取文件中的前一行,就无法读取或写入CSV来直接寻址任何行。
在没有解析行并解码所有值的情况下,无法读取或写入CSV来处理行中的值。
因此,编写CSV文件的任何练习都必然包括按顺序一次写一行,并按顺序再次写入该行的所有值。如果您有一个CSV文件并想要更改第9,542行中的第10个值,则必须读取整个文件,更改该值并再次写出该文件。