我是python的新手。在一個文件中有不同的端口號。我想遍歷端口號。端口用逗號分隔。最後,我想在該文件中附加我的端口號。我寫的代碼不起作用,因爲最後總會有換行符。我怎麼解決這個問題。有沒有更好的解決方案。這裏是我的代碼 -Python - 讀取,寫入並附加到文件
f = open("ports.txt", "r")
line = f.readline()
line = line.split(",")
print(line)
if len(line) > 0:
del line[-1]
for port in line:
print(port)
f = open("ports.txt", "a")
m = str(self.myPort)+","
f.write(m)
f.close()
感謝您的慷慨評論。我很抱歉問這個問題,但是在line.split(',')]中,「ports = [int(i)for line in inf for i是什麼意思? –
@ eddard.stark:對於ports.txt文件中的每一行,它將分隔逗號分隔的數字並將其轉換爲整數。然後它將它們全部返回到列表中。 –
感謝您的幫助。你很親切。 –