0

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)

2 Answers 2

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']
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.