我是新來的python,我嘗試了一個新問題,但無法獲得解決方案。我已經叫replace.txt與內容像這樣的文本文件:從另一個文本文件中替換文本文件中的行
81, 40.001, 49.9996, 49.9958
82, 41.1034, 54.5636, 49.9958
83, 44.2582, 58.1856, 49.9959
84, 48.7511, 59.9199, 49.9957
85, 53.4674, 59.3776, 49.9958
86, 57.4443, 56.6743, 49.9959
87, 59.7, 52.4234, 49.9958
現在我多了一個文件名爲實際數據,它有一個巨大的像上面這樣一個數據量現在我想更換以上通過在actualdata.txt匹配像搜索「81」的第一數目與具有「81」線replace.txt
這裏替換它在actualdata.txt線actualdata.txt看起來像這樣:
--------lines above--------
81, 40.0 , 50.0 , 50.0
82, 41.102548189607, 54.564575695695, 50.0
83, 44.257790830341, 58.187003960661, 50.0
84, 48.751279796738, 59.921728571875, 50.0
85, 53.468166336575, 59.379329520912, 50.0
86, 57.445611860313, 56.675542227082, 50.0
87, 59.701750075154, 52.424055585018, 50.0
88, 59.725876387298, 47.674633684987, 50.0
89, 57.511209176153, 43.398353484768, 50.0
90, 53.558991157616, 40.654756186166, 50.0
91, 48.853051436724, 40.06599229952 , 50.0
92, 44.335578609695, 41.75898487363 , 50.0
93, 41.139049269956, 45.364964707822, 50.0
94, 4.9858306110506, 4.9976785333108, 50.0
95, 9.9716298556132, 4.9995886389273, 50.0
96, 4.9712790759448, 9.9984071508336, 50.0
97, 9.9421696473295, 10.002460334272, 50.0
98, 14.957223264745, 5.0022762348283, 50.0
99, 4.9568005100444, 15.000751982196, 50.0
------lines below----------
我該怎麼做,請幫助我我試圖使用fileinput和取代,但我沒有得到輸出。
這是示例代碼我還在即興(一條線,這是工作的Fyn):
oldline=' 82, 41.102548189607, 54.564575695695, 50.0'
newline=' 81, 40.001, 49.9996, 49.9958'
for line in fileinput.input(inpfile, inplace = 1):
print line.replace(oldline,newline),
這是我最後寫的代碼:
replacefile= open('temp.txt','r')
for line1 in replacefile:
newline = line1.rstrip()
rl=newline
rl=rl.split()
search =rl[0]
with open(inpfile) as input:
intable = False
for line in input:
fill=[]
if line.strip() == "*NODE":
intable = True
if line.strip() == "---------------------------------------------------------------":
intable = False
if intable:
templine=(line.rstrip())
tl=line.rstrip()
tl= tl.split()
if tl[0] == search:
oldline=templine
for line2 in fileinput.input(inpfile, inplace = 1):
line2.replace(oldline,newline)
但我不能沒有得到輸出actualdata.txt的內容正在獲得deletd,幫助我這個 輸出我想要的是改變像這樣actualdata.txt:
-------lines above------
81, 40.001, 49.9996, 49.9958
82, 41.1034, 54.5636, 49.9958
83, 44.2582, 58.1856, 49.9959
84, 48.7511, 59.9199, 49.9957
85, 53.468166336575, 59.379329520912, 50.0
86, 57.445611860313, 56.675542227082, 50.0
87, 59.701750075154, 52.424055585018, 50.0
88, 59.725876387298, 47.674633684987, 50.0
89, 57.511209176153, 43.398353484768, 50.0
90, 53.558991157616, 40.654756186166, 50.0
-------lines below------
你可以改變你的文本文件到csv適當的修改?我的意思是,既然你有一個分隔符,我認爲'csv'可以幫助你以比讀取文件操作更簡單的方式。 – 2014-10-17 03:58:17
我無法控制它,因爲這是它以.txt格式提供的軟件的輸出文件而已@LearningNeverStops – user3887331 2014-10-17 04:06:53
好的,順便說一句,你嘗試了什麼?你提到你使用的文件輸入。你能提供代碼嗎? – 2014-10-17 04:14:52