+ 1
Help with the file’s project
file = open("/usercode/files/books.txt", "r") #tu código va aquí txt=" " for line in file: s=line.split(" ") for j in range(len(s)): k=s[j] l=k[0] txt= txt + str(l) print(txt) txt+="\n" file.close() What is wrong? I’m stuck, please help
5 ответов
+ 1
Mabel Zavala Moreira
Copy whole code and replace your code with this code and see
+ 3
Mabel Zavala Moreira ,
here is a version that differs a bit from yours, with an improved readability:
file = open("/usercode/files/books.txt", "r")
for line in file:
line = line.split()
res = "" # create an empty string for temporarly holding the first letters from each word
for word in line: # iterate through the lines
res += word[0] # take the first letter from each word in a specific line and adx it to the output string
print(res) # print the composed output string
file.close()
+ 2
Mabel Zavala Moreira
you have to reinitialise txt with empty character before the 2nd loop
And also no need to do txt += "\n"
file = open("/usercode/files/books.txt", "r")
#tu código va aquí
txt = " "
for line in file:
s = line.split(" ")
txt = ""
for j in range(len(s)):
k = s[j]
l = k[0]
txt= txt + str(l)
print(txt)
# txt+="\n"
file.close()
+ 1
True, thank you AJ
0
I applied the recommended changes but its not working :(