简体   繁体   中英

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\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:

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']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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