Simkill
Simkill

Reputation: 345

Reading and printing from a plain text file Python 3

I have a plain text file and I am trying to recreate the 'print as written' functionality of print using the text file.

The text file currently has:

"""
Test1

Test1

Test1
""",
"""
Test2

Test2

Test2
""",
"""
Test3

Test4

Test5
"""

And my aim is to read this into a list of 3 strings, have the random module select one of those strings and end up printing it exactly as written but without the """ or ,. I can remove those characters from the file if need be, I was just guessing on how to get print to print exactly what's written as it would with:

print("""
Test1

Test1

Test1
""")

(output)

Test1

Test1

Test1

Any help would be much appreciated. Thanks!

Edit: I have tried:

import random
file = open('prebaked', 'r')
print(random.choice(file))

and

import random
with open('prebaked', 'r') as f:
    file = f.read()
print(random.choice(file))

and

import random
with open('prebaked', 'r') as f:
    file = list(f.read())
print(random.choice(file))

Upvotes: 0

Views: 2339

Answers (2)

Peter Varo
Peter Varo

Reputation: 12180

Logic:

  • Read the file.
  • Separate strings into a list, based on ',' and remove white-spaces and """ from the strings.
  • Call random to choose from the list.

Code:

import random

with open('mytextfile.txt', 'r') as file_obj:
    str_list = [s.strip('\r\n\t "') for s in file_obj.read().split(',')]

print random.choice(str_list)

Upvotes: 3

interjay
interjay

Reputation: 110174

What your file contains is almost exactly the Python syntax for a list of strings, it's just missing the [ and ]. If you add these, you can use ast.literal_eval to safely evaluate the Python syntax and give you the list of strings:

>>> from ast import literal_eval
>>> with open('myfile.txt', 'r') as f:
        file_contents = f.read()
>>> literal_eval('[' + file_contents + ']')
['\nTest1\n\nTest1\n\nTest1\n', '\nTest2\n\nTest2\n\nTest2\n', '\nTest3\n\nTest4\n\nTest5\n']

Upvotes: 2

Related Questions