Python - 读取,写入和附加到文件

时间:2013-11-29 01:14:32

标签: python file file-io python-3.x

我是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 个答案:

答案 0 :(得分: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))

答案 1 :(得分: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)