2013-11-29 59 views
0

我是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() 

回答

2
# read port-list 
with open('ports.txt') as inf: 
    ports = [int(i) for line in inf for i in line.split(',')] 

# display ports 
for port in ports: 
    print(port) 

# recreate file 
ports.append(myPort) 
ports.sort() 
with open('ports.txt', 'w') as outf: 
    outf.write(','.join(str(p) for p in ports)) 
+0

感謝您的慷慨評論。我很抱歉問這個問題,但是在line.split(',')]中,「ports = [int(i)for line in inf for i是什麼意思? –

+0

@ eddard.stark:對於ports.txt文件中的每一行,它將分隔逗號分隔的數字並將其轉換爲整數。然後它將它們全部返回到列表中。 –

+0

感謝您的幫助。你很親切。 –

1

當逗號分隔值處理,你應該在一般使用csv module

下面的代碼應該是不言自明的。

import csv 

# By using the with statement, you don't have to worry about closing the file 
# for reading/writing. This is taken care of automaticly. 
with open('ports.txt') as in_file: 
    # Create a csv reader object from the file object. This will yield the 
    # next row every time you call next(reader) 
    reader = csv.reader(in_file) 

    # Put the next(reader) statement inside a try ... except block. If the 
    # exception StopIteratorion is raised, there is no data in the file, and 
    # an IOError is raised. 
    try: 
     # Use list comprehension to convert all strings to integers. This 
     # will make sure no leading/trailing whitespace or any newline 
     # character is printed to the file 
     ports = [int(port) for port in next(reader)] 
    except StopIteration: 
     raise IOError('No data in file!') 

with open('ports.txt', 'wb') as out_file: 
    # Create a csv writer object 
    writer = csv.writer(out_file) 
    # Append your port to the list of ports... 
    ports.append(self.myPort) 
    # ...and write the data to the csv file 
    writer.writerow(ports) 
+0

非常感謝您的答案。 –