Reputation: 135
Hi I'm trying to write a function that has a path to a .txt file as input and outputs a list of all the words in the file in Python 3. I apologise in advance for my lack of understanding and poor formatting.
I managed to open the file but cannot really work with it as I'd hoped. I tried just making a long string of the entire file and then use str.split(" ")
to get a list with all the words in the file. However, I just get <_io.TextIOWrapper
which I'm not even sure what it means even after searching it up. Additionally, I tried to use str.strip()
to get rid of the \n
but then I got the Errormessage: "<_io.TextIOWrapper" object has no attribute "split"
.
This is basically how I've tried opening the file so far and it did work. However, as previously mentioned I can't really make much more with it.
def do_sth(inp):
with open(inp,"r") as file:
Is there an easy way to just open .txt files and for example count the words or sentences etc? (I have done this before but only with a few senteces or words that were not in a file)
edit: more context: This is what I have come up so far. If i do it any other way it will just take each character of the words. The text file I'm working with is a long text and hence I need to somehow first get rid of the punctuation, and then split the text at each space so I have a list of words. Not really sure how to work with this.
def task(inp):
with open(inp,"r") as file:
contents = file.read()
words = contents.strip().split(" ")
while "\n" in words:
words.remove("\n")
print(words)
Upvotes: 0
Views: 197
Reputation: 432
f=open("file.txt", "r")
contents =f.read()
l = list(contents)
Now you got a list and can output that in your console
with print(l)
source: reading and writing files in python
Upvotes: 1