[Solved] File not found Error in reading text in python [duplicate]


Replace

fileref = open("H:\CloudandBigData\finalproj\BeautifulSoup\twitter.txt","r")

with

fileref = open(r"H:\CloudandBigData\finalproj\BeautifulSoup\twitter.txt","r")

Here, I have created a raw string (r""). This will cause things like "\t" to not be interpreted as a tab character.

Another way to do it without a raw string is

fileref = open("H:\\CloudandBigData\\finalproj\\BeautifulSoup\\twitter.txt","r")

This escapes the backslashes (i.e. "\\" => \).


An even better solution is to use the os module:

import os
filepath = os.path.join('H:', 'CloudandBigData', 'finalproj', 'BeautifulSoup', 'twitter.txt')
fileref = open(filepath, 'r')

This creates your path in an os-independent way so you don’t have to worry about those things.


One last note… in general, I think you should use the with construct you mentioned in your question… I didn’t in the answer for brevity.

6

solved File not found Error in reading text in python [duplicate]