开发者

Reading a file in Python without an extension

开发者 https://www.devze.com 2023-02-13 13:25 出处:网络
I want to read a (basically a text file) file without an ext开发者_开发知识库ension in Python 2.6. I have tried the following codes with the following errors..

I want to read a (basically a text file) file without an ext开发者_开发知识库ension in Python 2.6. I have tried the following codes with the following errors..

for infile in glob.glob(os.path.join(path + "Bookmarks",'*')):
    review_file = open(infile,'r').read()
    print review_file

-> global name glob is not defined

f = open(path, "r")
text = f.readlines()
print text

-> Prints "x00\x00\x00\x00\x00\" etc, and this is not what is inside of this file.

Edit: -> The conents of the file, directly, is what I want, for example if the file had "023492034blackriver0brydonmccluskey" in it, it would (as of now) extract it with a bunch of binary values, whereas I only want the exacy contents. How would I do so?


  1. If you want to use the glob module, you have to import it first:

    import glob
    for infile in glob.glob(os.path.join(path, '*')):
        review_file = open(infile,'r').read()
        print review_file
    
  2. Are you sure that your file does not contain the binary data you are getting?


Have you tried it opening in text mode. But as per the documentation, 'r' should have been synonym of 'rt'.

f = open(path, "rt")
text = f.readlines()
print text


Your current code looks at every file in the directory; if you only want files without an extension you should be using glob.glob('*.')


Based on the comments from the OP, the question needs to be rephrased along the lines of "I have a file with NULs in it, how do I get rid of them so I only see the text". To which the answer would be something like:

with open("myfile", 'rb') as f:
    data = f.read()
    clean_data = data.replace('\0', '')
    text = clean_data.decode('ascii') # Or other encoding, if text is not ASCII
0

精彩评论

暂无评论...
验证码 换一张
取 消