Reading a whole file into 1 string

Question:
I wanted to read a file into 1 string using the read() string method on the file handle but when I tried to use the print or len function on the variable to which I assigned the string, I don’t get any output, but when I use the file handle in a for loop, it does work.
Repl link:
https://replit.com/@AhmadBahja/FCC-Python#Practice.py

code snippet
1 Like

Hello @AhmadBahja welcome to the community!

You can use the seek() method on the file handle to reset the position to the start of the file after your for loop.
For example:

xfile = open('mbox.txt')

count = 0
for line in xfile:
    count = count + 1
print('Count:', count)

xfile.seek(0)  # Reset the position.
strg = xfile.read()
print(len(strg))

xfile.close()  # Always close the file.
5 Likes

You don’t need to if you use a context handler:

with open('mbox.txt') as file:
    print('Count:', len(file.readlines()))

    file.seek(0)
    print(len(file.read()))
3 Likes

My god, I never knew that. Thanks for the tip!

3 Likes

Thanks for your help. When I tried to search through the file using the startswith() method after I used the len function, I had to reset the position again using the seek() method. So, do I have reset the position each time I want to do something with the file?

Yes, when you read a file in Python, it’s kinda like when u r reading a book. If you read a book from start to finish and then want to read it again, you would have to turn back to the first page. So, when you read a file in Python, it maintains a file pointer that tracks where you are in the file. Each time you read from the file, the pointer moves forward, so if you want to read from the beginning again, you need to reset the position, and we did that using the seek() method.

2 Likes

print(‘hello sir welcome to KFC’)
print(‘what is your name’)
name= input('write you name here : ')
if name == ‘mike’ or name == ‘torres’:
print(‘are you ‘, name ,’ or other guy?’)
answer=input('yes/no : ')
elif answer == ‘yes’:
print(‘you are not welcome here,leave please’)
exit()
elif answer == ‘no’:
print (‘what is your lanst name?’)
last_nam = input('write your last name : ')
elif last_nam == ‘jeff’ or last_nam == ‘micheal’:
print(‘you are not welcome here,leave please’)
else:
print(‘welcome to KFC mr ‘, name ,’ nice to meet you’)
what is the problem with this code

Okay, I understand. Thanks very much for your help.

Hello @NuggetWorld, welcome to the community!

I ask that you open a new topic with your problem, so it doens’t get lost and it can be tracked by the community!

2 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.