将CSV文件转换为HTML表格时跳过列表

将CSV文件转换为HTML表格时跳过列表

问题描述:

我使用randomuser.me API生成随机用户CSV文件。 程序应该将CSV转换为HTML表格。 我试图跳过列[0, 3, 4]不会显示在生成的HTML表中。 为此,我尝试使用for-loopif-condition。 问题是循环中的变量column不是int,我无法创建条件if (int(column) == 0 and int(column) == 3 and int(column) == 4)。 我将非常感谢指出解决方案如何解决它。将CSV文件转换为HTML表格时跳过列表

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') 

您可以使用dellist中删除条目。所以,按相反的顺序,刚刚摆脱他们:

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

+0

是的,你是对的。应该是或声明。它仍然没有解决问题。 – Daniel

谢谢您的帮助。

奥斯汀黑斯廷斯说,我删除不CSV需要的列文件

for row in csvFile: 
    for column in [4,3,0]: 
     del row[column]