1

I'm trying to concatenate a string pulled from a file with a string literal and getting an error.

Example:

file.txt:

string1
string2
string3

program.py:

import random
f = open("file.txt", "r")
alist = f.readlines()
f.close()

anotherlist = ['word1', 'word2']
astring = random.choice(alist) + " " + random.choice(anotherlist)
print(astring)

It prints the variable it pulled from the .txt file, but it won't print anything after that.

BabaSvoloch
  • 301
  • 3
  • 20
  • 1
    Seems to work fine when I try to replicate. Are you sure there isn't something else affecting your program? How is `anotherlist` actually being initialized in your program? And are you sure that `anotherlist` doesn't contain an empty string as an element? – sshashank124 May 12 '18 at 09:19
  • it works fine from my end as well – Chukwuemeka Ihedoro May 12 '18 at 09:20
  • Lines read from files end with an *eoln*. Isn't the rest of the text printed on the next line? – CristiFati May 12 '18 at 09:23
  • That is true. You can try doing `random.choice(alist).strip()` to remove whitespaces from the front and back. Alternatively, you can do `alist = f.read().splitlines()` as explained here: https://stackoverflow.com/questions/12330522/reading-a-file-without-newlines – sshashank124 May 12 '18 at 09:25

0 Answers0