[英]Find, Replace, and Concatenate strings
經過 5 年以上的不活動,我只是重新(學習)python; 雖然我一開始並不擅長這並沒有幫助......這就是我想要做的:
兩組代碼分別按預期工作。 我嘗試了很多不同的方法將兩組代碼添加在一起,但沒有任何效果。
示例文件(C:\gcode\aaaa.gcode)
# start of file
some text
other text
# more text
G00 X1 Y1
G00 X2 Y2
# other text
G00 X3 Y3
G00 X4 Y4
#end of file
對於最終結果,我想要:
# start of file
some text
other text
# more text
G1 X1 Y1 Z0.3
G1 X2 Y2 Z0.3
# other text
G1 X3 Y3 Z0.3
G1 X4 Y4 Z0.3
#end of file
示例代碼/結果
Code:
with open(r'C:\gcode\aaaa.gcode', 'r') as fin, open(r'C:\gcode\bbbb.gcode', 'w') as fout:
for line in fin:
if line.startswith('G00'):
fout.write(line[:-1] + ' Z0.3' + '\r')
else:
fout.write(line)
Result:
# start of file
some text
other text
# more text
G1 X1 Y1
G1 X2 Y2
# other text
G1 X3 Y3
G1 X4 Y4
#end of file
Code:
with open(r'C:\gcode\aaaa.gcode', 'r') as fin, open(r'C:\gcode\bbbb.gcode', 'w') as fout:
for line in fin:
if line.startswith('G00'):
fout.write(line[:-1] + ' Z0.3' + '\r')
else:
fout.write(line)
Result
# start of file
some text
other text
# more text
G00 X1 Y1 Z0.3
G00 X2 Y2 Z0.3
# other text
G00 X3 Y3 Z0.3
G00 X4 Y4 Z0.3
#end of file
我已經嘗試了下面代碼的各種分支,但我總是收到以下錯誤消息:
with open(r'C:\gcode\aaaa.gcode', 'r') as fin, open(r'C:\gcode\bbbb.gcode', 'w') as fout:
for line in fin:
if line.startswith('G00'):
fout.write(line[:-1] + ' Z0.3' + '\r')
fout = fout.replace('G00', 'G1') # newly added line
else:
fout.write(line)
AttributeError: '_io.TextIOWrapper' object has no attribute 'replace'
您正在嘗試在文件句柄上執行.replace
- 這沒有意義,您應該line
執行,例如:
with open(r'C:\gcode\aaaa.gcode', 'r') as fin, open(r'C:\gcode\bbbb.gcode', 'w') as fout:
for line in fin:
line = line.replace('G00', 'G1')
if line.startswith('G00'):
fout.write(line[:-1] + ' Z0.3' + '\r')
else:
fout.write(line)
另請注意,當且僅當行以\r
分隔時,您的代碼才能正常工作。
您不能從fout
替換,您需要替換該行的內容。 你為什么要設置為等於fout.replace('G00', 'G1') # newly added line
也是沒有意義的。 嘗試這個:
with open(r'C:\gcode\aaaa.gcode', 'r') as fin, open(r'C:\gcode\bbbb.gcode', 'w') as fout:
for line in fin:
if line.startswith('G00'):
fout.write(line[:-1] + ' Z0.3' + '\r')
new_line = line('G00', 'G1') # newly added line
# I believe you're trying to add this new line to the document
fout.write(new_line)
else:
fout.write(line)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.