My strip() in Python is showing an error. I copied and pasted this code from GeeksForGeeks:
# Python program to
# demonstrate reading files
# using for loop
L = ["Geeks\n", "for\n", "Geeks\n"]
# Writing to file
file1 = open('myfile.txt', 'w')
file1.writelines(L)
file1.close()
# Opening file
file1 = open('myfile.txt', 'r')
count = 0
# Using for loop
print("Using for loop")
for line in file1:
count = 1
print("Line{}: {}".format(count, line.strip()))
# Closing files
file1.close()
Turned it into this:
compfile = open(input('path:'), 'r')
count = 0
for line in compfile:
count = 1
print("Line{}: {}".format(count,
compfile.strip()))
compfile.close()
But it's showing this error:
Traceback (most recent call last):
File "....", line 5, in <module>
print("Line{}: {}".format(count, compfile.strip()))
AttributeError: '_io.TextIOWrapper' object has no attribute 'strip'
CodePudding user response:
It has to be line.strip()
not compfile.strip()
compfile = open(input('path:'), 'r')
count = 0
for line in compfile:
count = 1
print("Line{}: {}".format(count, line.strip()))
compfile.close()
The error is because you tried using strip()
on the file object and it doesn't have the attribute strip