2013-11-29 4 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

Благодарим вас за щедрый комментарий. Мне жаль это спрашивать, но что означает «ports = [int (i) для строки в inf для i в line.split (',')]" означает? –

+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

спасибо за ваш ответ. –

Смежные вопросы