長時間潛伏者,第一次海報。 我尋找了一些解決方案,並沒有找到符合我需求的東西。Python 3.2:.txt到xml.txt
我的分配如下:例如輸入文件
student.txt
內容:
John Smith
Harvard
4.00
1600
「你的任務是寫一個Python程序,稱爲批號(文件名),即以文件名作爲參數,它將打開文件並創建一個帶有標記數據的新文件,上面示例文件的輸出如下:「
<applicant>
<name> John Smith </name>
<school> Harvard </school>
<gpa> 4.00 </gpa>
<sat> 1600 </sat>
</applicant>
另外:輸出文件的名稱與正在打開的文件的名稱相似。如果輸入的是student.txt,該出將studentXML.txt
我試圖用我的手切片(從另一個海報借用了這個):
tags = ['name', 'university', 'gpa', 'sat'] #Add desired
tags xml = ''#Add xml parsing with open("data.txt") as data:
#read data and filter out whitespace
lines = [line.strip() for line in data.readlines()]
#Generating xml tags via slicing
xml = '\n'.join(['<{0:s}> {1:s} </{0:s)>'.format(tag, value)
for tag, value in zip(tags, lines)])
任何幫助將不勝感激。我很抱歉沒有編輯能力。
追溯,使用「data.txt」作爲文件。 (在同一文件夾中的項目):
回溯(最近通話最後一個): 文件 「C:\用戶\ Rokudoル\ Dropbox的\ 22c005 \ Python項目XML generation.py」,7號線,在 建宏.IOError:[錯誤2]沒有這樣的文件或目錄:糾正代碼
with open(fileName) as data:
#Read data and filter out whitespace
lines = [line.strip() for line in data.readlines()]
# Generating xml tags via slicing
xml = '\n'.join(['<{0:s}> {1:s} </{0:s}>'.format(tag, value)
for tag, value in zip(tags, lines)])
print xml
「的data.txt」
後,我得到一個回調的打印語句。
回溯: 回溯(最近通話最後一個): 文件 「C:\用戶\ foobar的\ XML generation.py」,第15行,在 語法錯誤:打印的xml:C:\用戶\ foobar的\ XML generation.py,line 1513
使用「return xml」編輯將其拍攝到shell中。 某些格式問題會修補並查看會發生什麼。
那麼,你的代碼是如何失敗的呢?請提供追溯。這裏有一些錯誤,但很難判斷它們是否在你正在執行的代碼中,或者只是通過使用StackOverflow編輯器發佈來引入格式化問題。 –
追加追溯。 – Yarou
這不是問題,但是你的'xml ='\ n'.join()'調用會失敗,因爲你有不平衡的括號。你使用'<{0}> {1}{0)>'(最後一個花括號實際上是一個paren) –