문제

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