2012-11-25 5 views
1

Excel에서 읽은 여러 행의 데이터 목록이 있습니다. 그런 다음 목록으로 읽습니다. 이제이 목록을 다른 텍스트 파일로 인쇄하여 저장 한 다음 html을 다른 파일로 인쇄하고 싶습니다. 그럼 테이블을 만들 수 있도록 html 파일을 만들고 싶습니다. 그래서 4 행이 있고 각 행에는 데이터 셀이 하나씩 들어 있습니다.파이썬에서 파일로 목록을 인쇄하는 방법

참고 : 나는 지금까지이 시도 파이썬 3

를 사용하고 있지만 작동하지 않습니다.

data = ['Course name', 'Course Type', 'Tutor'] 
     ['English', , 'Languages' , 'Mr A'] 
     ['Geography' , 'Humanities', 'Mr B'] 
     ['Civil Engineering' , 'Engineering', 'Mr C'] 

f = open("SomeData.csv", 'w') 
for row in mylist: 
    print(row,file=f) 
+1

'데이터'를 하나의 목록으로 표시하고 일부 "알몸"목록으로 표시하지만 루프에 'mylist'를 사용합니다. – Keith

+2

csv 파일을 작성하는'csv' 모듈에 좋은 생각입니다. 그렇다면 필드 중 하나에 이스케이프해야하는 문자가 포함되어 있어도 걱정할 필요가 없습니다. –

답변

3

귀하의 코드 목록 초기화로 변환 :

data = ['Course name', 'Course Type', 'Tutor'] 

['English', , 'Languages' , 'Mr A']    # Just a statement 
['Geography' , 'Humanities', 'Mr B']    # Just a statement 
['Civil Engineering' , 'Engineering', 'Mr C']  # Just a statement 

하지만 당신은리스트의 목록을 확인해야합니다, 당신은 파일에 데이터를 기록 할 수 있습니다

data = [ 
    ['Course name', 'Course Type', 'Tutor'], 
    ['English', 'Languages' , 'Mr A'], 
    ['Geography', 'Humanities', 'Mr B'], 
    ['Civil Engineering', 'Engineering', 'Mr C'] 
] 

다음을 :

f = open("output.txt", "w") 
for row in data: 
    print(", ".join(row), file=f) 
f.close() 
+1

'print (",".join (row), file = f)'와 같이 내부 루프를 피할 수 있습니다. – jdi

+0

학생 ID를 추가하기로 결정했지만 목록 인덱스가 터플이 아닌 정수 여야한다는 오류가 발생합니다. '['학생 ID ','코스 이름 ','코스 유형 ','교사 '], ['12345 ','영어 ','언어 ','Mr A '], ['34598 ' , 'Geography', 'Humanities', 'Mr B'], [ '23976', '토목 공학', '엔지니어링', '미스터 C'] ] – Arcytoi

+0

@jdi, thks, 내가 편집했습니다. – kaspersky

2

ctly 바와 같이 상기 질문에 명시한 바와 같이, 출력 부 할 수있는 조립 또는 이런 : 여기

f = open("SomeData.csv", 'w') 
for row in data: 
    f.write(",".join(row)+",") 
f.close() 

는 CSV와 같은 방식으로 HTML 출력 부 할 쉬운 방법에 대한 힌트 인 일부. http://docs.python.org/3.3/library/csv.html

+0

고마워요. 해봤지만, 페이지를로드 할 때 테이블 형식으로 표시되지 않고 공백없이 서로 옆에 표시됩니다. – Arcytoi

+0

당신은 여전히 ​​"" – icey502

+0

내가' ""+ "".join (행) 생각하지 않는다 ... 즉, 그것을 합법적 인 문서를 만들기 위해

태그를 필요 + 것 '당신이 기대하는 것과 필요한 것을합니다. – martineau

1
#!/usr/bin/env python3 
# -*- coding: utf-8 -*- 

import csv 

class CoolFileWriter: 
    """reads a csv file and writes a text or html file""" 
    def __init__(self, csv_file, txt_out='out.txt', html_out='out.html'): 
     self.csv_file = csv_file 
     self.txt_out = txt_out 
     self.html_out = html_out 
     self.content = [] 

    def read_csv(self): 
     with open(self.csv_file, newline='') as f: 
      reader = csv.reader(f) 
      for row in reader: 
       self.content.append(row) 

    def write_txt(self): 
     f = open(self.txt_out, 'w') 
     for row in self.content: 
      f.write(', '.join(row) + '\n') 
     f.close() 

    def write_html(self): 
     html_pre=""" 
<!DOCTYPE HTML> 
<html lang="en"> 
<head> 
<meta charset="UTF-8"> 
<title>Table Data</title> 
<style> 
#newspaper-a 
{ 
    font-family: "Lucida Sans Unicode", "Lucida Grande", Sans-Serif; 
    font-size: 12px; 
    margin: 45px; 
    width: 480px; 
    text-align: left; 
    border-collapse: collapse; 
    border: 1px solid #69c; 
} 
#newspaper-a th 
{ 
    padding: 12px 17px 12px 17px; 
    font-weight: normal; 
    font-size: 14px; 
    color: #039; 
    border-bottom: 1px dashed #69c; 
} 
#newspaper-a td 
{ 
    padding: 7px 17px 7px 17px; 
    color: #669; 
} 
</style> 
</head> 
<body> 
<table id="newspaper-a"> 
""" 
     html_post=""" 
</table> 
</body> 
</html> 
""" 
     f = open(self.html_out, 'w') 
     f.write(html_pre) 
     th=True 
     for row in self.content: 
      if (th): 
       f.write("<tr>\n\t<th>"+"</th>\n\t<th>".join(row)+"</th>\n</tr>\n") 
       th=False 
      else: 
       f.write("<tr>\n\t<td>"+"</td>\n\t<td>".join(row)+"</td>\n</tr>\n") 
     f.write(html_post) 
     f.close() 

f = CoolFileWriter('excel.csv', 'data.txt', 'data.html') 

f.read_csv() 
f.write_txt() 
f.write_html() 

테이블 스타일 here에서 온다 :

f = open("output.html", 'w') 
f.write("<html><table>") 
for row in data: 
    f.write("<tr><td>"+"</td><td>".join(row)+"</td></tr>") 
f.write("</table></html>") 
f.close() 

또한 깊이있는 CSV가 필요 이상으로 도움이되는 파이썬 CSV 라이브러리가있다. :-)

관련 문제