简体   繁体   English

将文本文件的一行存储为数组 python

[英]storing one line of a text file as an array python

i have a text file which is set out like:我有一个文本文件,其内容如下:

a 1 1
b 1 1
c 1 1
d 1 1
e 1 1
f 1 1

and i was hoping to out put it like ["a", "1", "1"] etc however it currently outputs as我希望像 ["a", "1", "1"] 等那样输出它,但它目前输出为

[a 1 1\n]
[b 1 1\n]
[c 1 1\n]
[d 1 1\n]
[e 1 1\n]
[f 1 1\n] 

my code is我的代码是

import csv
tname = input("player 1 enter your team name ")
x = "./" + tname + ".txt"
with open (x, "r") as r:
    reader = csv.reader(r)
    for row in r:
        spec = [row]
        print (spec)

No need to use the csv module, just read all the lines in turn, split them by spaces and append them to your output list:无需使用csv模块,只需依次读取所有行,用空格和 append 将它们分隔到您的 output 列表中:

with open('input.txt', 'r') as f:
    lines = f.readlines()

output = []
for line in lines:
    output = output + line.split()

print(output)

This gives you:这给了你:

['a', '1', '1', 'b', '1', '1', 'c', '1', '1', 'd', '1', '1', 'e', '1', '1', 'f', '1', '1']

There is some ambiguity what is the desired result.期望的结果是什么存在一些歧义。 So three possible answers:所以三个可能的答案:

with open('somefile.txt', 'r') as f:
    for row in f:
        print(row.strip().split())

# -> ['a', '1', '1']
     ['b', '1', '1']
     ['c', '1', '1']
     ['d', '1', '1']
     ['e', '1', '1']
     ['f', '1', '1']

with open('somefile.txt', 'r') as f:
    print([row.strip().split() for row in f])

# -> [['a', '1', '1'], 
      ['b', '1', '1'], 
      ['c', '1', '1'], 
      ['d', '1', '1'], 
      ['e', '1', '1'], 
      ['f', '1', '1']]

with open('somefile.txt', 'r') as f:
    print([item for row in f for item in row.strip().split()])

# -> ['a', '1', '1', 'b', '1', '1', 'c', '1', '1', 'd', '1', '1', 'e', '1', '1', 'f', '1', '1']

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

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