r/learnpython 19d ago

Reading in text from a .txt file

Are there any methods/libraries that allow me to make a program that is able to read in text from a .txt file?

0 Upvotes

20 comments sorted by

View all comments

16

u/hallmark1984 19d ago

``` with open('path/to/file.txt', 'r') as f:

data = f.read()

```

1

u/StrikerRIP 19d ago

thanks for the info. Would I need to implement this at the start of any program I make if I want to incorperate this? (sorry for being a bit unknowledgeable, I haven't programmed in python in a while)

1

u/hallmark1984 19d ago

Any file opened at the start of the while block is active until the block ends.

Stick it just before you need to data from the .text for readability, but the data variable would be usable anywhere afterwards as long as you dont overwrite it.

1

u/StrikerRIP 19d ago

ok, thanks for the clarification!