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.

有帮助吗?

解决方案

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,

其他提示

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top