Pergunta

palavra = raw_input('palavra: ')    
arquivo = open('palavras.txt', 'r+')
lendo = arquivo.readline()
print palavra + lendo
arquivo.close()

I want to concatenate each line of the "palavras.txt" with the value of the variable "palavra" but in the code above it's only concatenating with one line and the rest is read but isn't concatenated.

Foi útil?

Solução

The problem is that you don't iterate through the other lines

with open('palavras.txt', 'r+') as f:
    for lendo in f:
        print palavra + lendo,

Outras dicas

read the whole of the file first

for line in arquivo.readlines():
    palavra = palavra+line

print palavra
with open('palavras.txt') as palavrasFile:
  print palavras.join(palavrasFile)

Use

  print palavras + palavras.join(palavrasFile)

if you want the prepend the value of palavras also to the first line. Spec isn't too clear on this.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top