0

I have an input file - file.txt :

guten
('nine', 'november')
('six', 'nine')
0
end

My python program is:

aa = []
with open('file.txt', 'r') as F1:
    for line in F1:
       line = line.rstrip('\n')
       aa.append(line)
    print aa

I am getting the output as:

['guten', "('nine', 'november')", "('six', 'nine')", '0', 'end', '']

But my expected output is:

['guten', ('nine', 'november'), ('six', 'nine'), '0', 'end', '']

Can someone tell me where I am going wrong ? Your help will be useful. Thanks in advance.

8
  • 5
    Can you explain precisely, what rules you want to use to sort the data, and what rules you want to use to interpret the input? It seems you want lines that are enclosed in () in the text file to turn into tuples, even though that text file is not Python code? But you want numbers to stay as strings? Commented Dec 11, 2014 at 0:51
  • Thanks for the reply. I have modified the question. I want this output so that I can sort and get the final result. Can u help me ?? Commented Dec 11, 2014 at 0:58
  • try running this sorted(['b', 'a', 'f', 'd', 'e', (3, 4), 1, 4, 5]) Commented Dec 11, 2014 at 0:58
  • Your expected output doesn't seem to sort the input at all. Are you really looking for a way to turn the strings on lines 2 and 3 into tuples? Commented Dec 11, 2014 at 1:00
  • Sort, but what criteria? Commented Dec 11, 2014 at 1:00

1 Answer 1

3

Although I can't really imagine how this would be useful, the following will do what you're asking for (given the limited data in the file you've given us):

import ast
aa = []
with open('file.txt', 'r') as F1:
    for line in F1:
        line = line.rstrip('\n')
        if line.startswith('('):
            aa.append(ast.literal_eval(line))  # turn tuple strings into tuples
        else:
            aa.append(line)       
    print aa
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.