【问题标题】:Python - read, write and append to a filePython - 读取、写入和附加到文件
【发布时间】:2013-11-29 01:14:31
【问题描述】:

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

【问题讨论】:

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


    【解决方案1】:
    # 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))
    

    【讨论】:

    • 感谢您的慷慨评论。很抱歉问这个问题,但是“ ports = [int(i) for line in inf for i in line.split(',')] ”是什么意思?
    • @eddard.stark:对于 ports.txt 文件中的每一行,它会拆分逗号分隔的数字并将每个数字转换为整数。然后它将所有这些都返回到一个列表中。
    • 最好使用csv模块的方法来提取值,而不是重新发明轮子
    【解决方案2】:

    在处理逗号分隔值时,通常应使用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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-07-20
      • 1970-01-01
      • 2016-10-27
      • 1970-01-01
      • 1970-01-01
      • 2012-11-12
      • 1970-01-01
      相关资源
      最近更新 更多