简体   繁体   English

python-在列表中逐行写入元组

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

My issue is to write what is in my file, row by row in my function. 我的问题是在函数中逐行写入文件中的内容。

Here's my code: 这是我的代码:

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

that return's all in a row, and I want each tuple in a single row. 返回的结果都是连续的,我希望每个元组都排成一行。

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

I want something similar to this: 我想要类似的东西:

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

You can use pprint . 您可以使用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)]

This is not an answer but a remark. 这不是答案,而是一句话。 You can reduce your code drastically by using a list comprehension: 您可以通过使用列表理解来大幅减少代码:

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

How about changing those 4 lines to: 如何将这4行更改为:

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

Or why not a full remake: 或者为什么不进行完整的翻拍:


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")

Now to your actual question. 现在是您的实际问题。 The operators is a list with tuples. 运算符是带有元组的列表。 You cannot format variables in Python. 您无法在Python中格式化变量。 It is only when you print or write that you have that option. 只有在打印或书写时才具有该选项。

Sample: this writes each tuple in separate lines to xyz.txt 示例:这会将每个元组以单独的行写入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")

I think all you need to do is: 我认为您需要做的是:

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

I also dont understand why you have those two lines? 我也不明白你为什么有这两行? Unless I've mistaken, if anyone cares to explain :) But those line can be made redundant completely. 除非我弄错了,否则如果有人在乎解释:)但是这些行可以完全多余。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM