[英]Skip columns while converting CSV file to HTML table
我正在使用randomuser.me API
生成随机用户CSV文件。 程序应该将CSV转换为HTML表。 我试图跳过列[0, 3, 4]
使其不显示在生成的HTML表中。 为此,我尝试使用for-loop
和if-condition
。 问题是循环中的变量column
不是int
并且if (int(column) == 0 and int(column) == 3 and int(column) == 4)
则无法创建条件。 我非常感谢您指出解决方案的解决方案。
import webbrowser
import csv
import sys
import requests
if len(sys.argv) < 2:
print("Usage: project.py <htmlFile>")
exit(0)
url = 'https://randomuser.me/api/?results=2&format=csv&inc=name,picture'
with requests.Session() as s:
download = s.get(url)
decodedContent = download.content.decode('utf-8')
csvFile = list(csv.reader(decodedContent.splitlines(), delimiter=','))
# Create the HTML file
htmlFile = open(sys.argv[1], "w")
# Fills up HTM code
# Remove BOM from UTF-8 (wierd symbols in the beggining of table)
htmlFile.write('<html><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><link rel="stylesheet" type="text/css" href="style.css"><head><title>Tabela</title></head><body><table>')
# Read a single row from the CSV file
for row in csvFile:
# Create a new row in the table
htmlFile.write('<tr>');
# For each column
for column in row:
if (int(column) == 0 and int(column) == 3 and int(column) == 4):
continue
else:
htmlFile.write('<td>' + column + '</td>')
htmlFile.write('</tr>')
htmlFile.write('</table></body></html>')
webbrowser.open_new_tab('index.html')
您可以使用del
从list
删除条目。 因此,以相反的顺序,只需摆脱它们:
for c in [4,3,0]:
del row[c]
使用反向顺序很重要,因为从列表中删除项目会更改该项目之后所有项目的编号。 所以总是从最后到第一个。
我不熟悉您使用的RandomUser API,但是从逻辑上讲,我不希望以下语句为真:
int(column) == 0 and int(column) == 3 and int(column) == 4
列可以同时等于所有这些值吗? 似乎不太可能。 我期望列要么是第0列或第3列或第4栏。
谢谢您的帮助。
正如Austin Hastings所说,我删除了CSV文件中不需要的列
for row in csvFile:
for column in [4,3,0]:
del row[column]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.