簡體   English   中英

python-在列表中逐行寫入元組

[英]python - write row by row tuples inside a list

我的問題是在函數中逐行寫入文件中的內容。

這是我的代碼:

def read_operators_file(file_name):
"""Read a file with operators into a collection.

Requires: file_name, str with the name of a text file with a list of operators.
Ensures: list, with the operators in the file; each operators is a tuple with the various element 
concerning that operator, in the order provided in the file.
"""
inputFile1 = open("operators14h55.txt",'r+')
import constants
for i in range(constants.HEADER_TOTAL_LINES):  # read some lines to skip the header
    inputFile1.readline()
operators = []
for line in inputFile1:
    name, language, domain, last_hour, total_minutes = line.strip().split(', ')
    operators.append((name, language, domain, last_hour, total_minutes))
inputFile1.close()
return operators

返回的結果都是連續的,我希望每個元組都排成一行。

[('Henry Miller', 'english', 'laptops', 'premium', 3), ('François Greenwich', 'spanish', 'cameras', 'premium', 6), ('Ricardo Carvalho', 'portuguese', 'refrigerators', 'premium', 2)]

我想要類似的東西:

[('Henry Miller', 'english', 'laptops', 'premium', 3), 
 ('François Greenwich', 'spanish', 'cameras', 'premium', 6), 
 ('Ricardo Carvalho', 'portuguese', 'refrigerators', 'premium', 2)]

您可以使用pprint

from pprint import pprint

operators = [('Henry Miller', 'english', 'laptops', 'premium', 3), ('François Greenwich', 'spanish', 'cameras', 'premium', 6), ('Ricardo Carvalho', 'portuguese', 'refrigerators', 'premium', 2)]
pprint(source)

# results
[('Henry Miller', 'english', 'laptops', 'premium', 3),
 ('François Greenwich', 'spanish', 'cameras', 'premium', 6),
 ('Ricardo Carvalho', 'portuguese', 'refrigerators', 'premium', 2)]

這不是答案,而是一句話。 您可以通過使用列表理解來大幅減少代碼:

operators = []
for line in inputFile1:
    name, language, domain, last_hour, total_minutes = line.strip().split(', ')
    operators.append((name, language, domain, last_hour, total_minutes))

如何將這4行更改為:

operators = [tuple(line.strip().split(', ')) for line in inputFile1]

或者為什么不進行完整的翻拍:


import constants # imports are always made first (very few exceptions)

def read_operators_file(file_name):
    """Read a file with operators into a collection.

    Requires: file_name, str with the name of a text file with a list of operators.
    Ensures: list, with the operators in the file; 
             each operators is a tuple with the various element 
             concerning that operator, in the order provided in the file.
    """

    with open(file_name,'r+') as inputFile1: # with ensures file closes, no need to worry
        # read some lines to skip the header
        for i in range(constants.HEADER_TOTAL_LINES):  
            next(inputFile1)
        operators = [tuple(line.strip().split(', ')) for line in inputFile1]

    return operators

# Function call
operators1 = read_operators_file("operators14h55.txt")

現在是您的實際問題。 運算符是帶有元組的列表。 您無法在Python中格式化變量。 只有在打印或書寫時才具有該選項。

示例:這會將每個元組以單獨的行寫入xyz.txt

l=[('Henry Miller', 'english', 'laptops', 'premium', 3), ('François Greenwich', 'spanish', 'cameras', 'premium', 6), ('Ricardo Carvalho', 'portuguese', 'refrigerators', 'premium', 2)]

with open('xyz.txt', 'w') as f:
    for x in l:
        f.write(str(x) + "\n")

我認為您需要做的是:

list_of_tuples = [(1,2),(4,5),(5,6)]
with open("out.txt") as new_file:
    new_file.write("\n".join( str(tuple) for tuple in list_of_tuples)
for i in range(constants.HEADER_TOTAL_LINES):  # read some lines to skip the header
    inputFile1.readline()

我也不明白你為什么有這兩行? 除非我弄錯了,否則如果有人在乎解釋:)但是這些行可以完全多余。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM