Python: Open function cannot read file











up vote
1
down vote

favorite












I'm using python 3.6. I am trying to read a lot of (.txt) files in multiple directories. Some files have a comma in the file name, e.g. 'Proposal for Anne, Barry and Carol.txt'.



The following code:



for filepath in glob.iglob(params.input_dir + r'****.*', recursive=True):
# [not shown here: code that filters on .txt filetype]

with open(filepath) as f:
for line in f:
for word in re.findall(r'w+', line):
# do stuff


Gives me an error on reading that file:



Traceback (most recent call last):
File "dir_scraper.py", line 50, in <module>
results_new = scraper.scrape_file(filepath)
File "C:Projectsscraper.py", line 33, in scrape_file
return func(filepath)
File "C:Projectsscraper.py", line 15, in txt
with open(filepath) as f:
FileNotFoundError: [Errno 2] No such file or directory: 'Z:\groups\Proposal for Anne, Barry and Carol.txt'


I do not want to edit the names of the files.



How can I properly read the files with comma's in the filenames?



Edit:




  • I'm sure the path exists.


  • Other files from the same directory are parsed without issues.


  • Trying to open the file directly from the commandline also gives: The system cannot find the path specified.


  • Also, I seem to be unable to rename the file, if I try to change the name through Windows File Explorer to remove the comma (or change something else), it is reset to the original filename.


  • Could it have something to do with file permissions?


  • Or maybe is the filename too long? The full path from Z:[..] to [..].txt is 270 characters long.










share|improve this question




















  • 3




    I cannot reproduce this behavior with Python 3.6.3. Can you show where the variable filepath is set?
    – elzell
    Nov 20 at 10:14






  • 1




    Maybe if you use listdir on the directory you can see what the file is actually called.
    – khelwood
    Nov 20 at 10:15










  • Check the file name correctly, we don't usually need to escape/handle comma names in the file name or any parameter string.
    – Shariq
    Nov 20 at 10:18










  • Are you sure your path Z:\groups exists ?
    – Dinko Pehar
    Nov 20 at 10:21










  • I'm sure the path exists. Other files from the same directory are parsed without issues. Directly from the commandline, trying to open the file also gives: The system cannot find the path specified. Also, I seem to be unable to rename the file, if I try to change the name through Windows File Explorer to remove the comma (or change something else), it is reset to the original filename.
    – Phantom
    Nov 20 at 10:27

















up vote
1
down vote

favorite












I'm using python 3.6. I am trying to read a lot of (.txt) files in multiple directories. Some files have a comma in the file name, e.g. 'Proposal for Anne, Barry and Carol.txt'.



The following code:



for filepath in glob.iglob(params.input_dir + r'****.*', recursive=True):
# [not shown here: code that filters on .txt filetype]

with open(filepath) as f:
for line in f:
for word in re.findall(r'w+', line):
# do stuff


Gives me an error on reading that file:



Traceback (most recent call last):
File "dir_scraper.py", line 50, in <module>
results_new = scraper.scrape_file(filepath)
File "C:Projectsscraper.py", line 33, in scrape_file
return func(filepath)
File "C:Projectsscraper.py", line 15, in txt
with open(filepath) as f:
FileNotFoundError: [Errno 2] No such file or directory: 'Z:\groups\Proposal for Anne, Barry and Carol.txt'


I do not want to edit the names of the files.



How can I properly read the files with comma's in the filenames?



Edit:




  • I'm sure the path exists.


  • Other files from the same directory are parsed without issues.


  • Trying to open the file directly from the commandline also gives: The system cannot find the path specified.


  • Also, I seem to be unable to rename the file, if I try to change the name through Windows File Explorer to remove the comma (or change something else), it is reset to the original filename.


  • Could it have something to do with file permissions?


  • Or maybe is the filename too long? The full path from Z:[..] to [..].txt is 270 characters long.










share|improve this question




















  • 3




    I cannot reproduce this behavior with Python 3.6.3. Can you show where the variable filepath is set?
    – elzell
    Nov 20 at 10:14






  • 1




    Maybe if you use listdir on the directory you can see what the file is actually called.
    – khelwood
    Nov 20 at 10:15










  • Check the file name correctly, we don't usually need to escape/handle comma names in the file name or any parameter string.
    – Shariq
    Nov 20 at 10:18










  • Are you sure your path Z:\groups exists ?
    – Dinko Pehar
    Nov 20 at 10:21










  • I'm sure the path exists. Other files from the same directory are parsed without issues. Directly from the commandline, trying to open the file also gives: The system cannot find the path specified. Also, I seem to be unable to rename the file, if I try to change the name through Windows File Explorer to remove the comma (or change something else), it is reset to the original filename.
    – Phantom
    Nov 20 at 10:27















up vote
1
down vote

favorite









up vote
1
down vote

favorite











I'm using python 3.6. I am trying to read a lot of (.txt) files in multiple directories. Some files have a comma in the file name, e.g. 'Proposal for Anne, Barry and Carol.txt'.



The following code:



for filepath in glob.iglob(params.input_dir + r'****.*', recursive=True):
# [not shown here: code that filters on .txt filetype]

with open(filepath) as f:
for line in f:
for word in re.findall(r'w+', line):
# do stuff


Gives me an error on reading that file:



Traceback (most recent call last):
File "dir_scraper.py", line 50, in <module>
results_new = scraper.scrape_file(filepath)
File "C:Projectsscraper.py", line 33, in scrape_file
return func(filepath)
File "C:Projectsscraper.py", line 15, in txt
with open(filepath) as f:
FileNotFoundError: [Errno 2] No such file or directory: 'Z:\groups\Proposal for Anne, Barry and Carol.txt'


I do not want to edit the names of the files.



How can I properly read the files with comma's in the filenames?



Edit:




  • I'm sure the path exists.


  • Other files from the same directory are parsed without issues.


  • Trying to open the file directly from the commandline also gives: The system cannot find the path specified.


  • Also, I seem to be unable to rename the file, if I try to change the name through Windows File Explorer to remove the comma (or change something else), it is reset to the original filename.


  • Could it have something to do with file permissions?


  • Or maybe is the filename too long? The full path from Z:[..] to [..].txt is 270 characters long.










share|improve this question















I'm using python 3.6. I am trying to read a lot of (.txt) files in multiple directories. Some files have a comma in the file name, e.g. 'Proposal for Anne, Barry and Carol.txt'.



The following code:



for filepath in glob.iglob(params.input_dir + r'****.*', recursive=True):
# [not shown here: code that filters on .txt filetype]

with open(filepath) as f:
for line in f:
for word in re.findall(r'w+', line):
# do stuff


Gives me an error on reading that file:



Traceback (most recent call last):
File "dir_scraper.py", line 50, in <module>
results_new = scraper.scrape_file(filepath)
File "C:Projectsscraper.py", line 33, in scrape_file
return func(filepath)
File "C:Projectsscraper.py", line 15, in txt
with open(filepath) as f:
FileNotFoundError: [Errno 2] No such file or directory: 'Z:\groups\Proposal for Anne, Barry and Carol.txt'


I do not want to edit the names of the files.



How can I properly read the files with comma's in the filenames?



Edit:




  • I'm sure the path exists.


  • Other files from the same directory are parsed without issues.


  • Trying to open the file directly from the commandline also gives: The system cannot find the path specified.


  • Also, I seem to be unable to rename the file, if I try to change the name through Windows File Explorer to remove the comma (or change something else), it is reset to the original filename.


  • Could it have something to do with file permissions?


  • Or maybe is the filename too long? The full path from Z:[..] to [..].txt is 270 characters long.







python windows filenames






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 20 at 11:04









Håken Lid

10.5k62441




10.5k62441










asked Nov 20 at 10:10









Phantom

114




114








  • 3




    I cannot reproduce this behavior with Python 3.6.3. Can you show where the variable filepath is set?
    – elzell
    Nov 20 at 10:14






  • 1




    Maybe if you use listdir on the directory you can see what the file is actually called.
    – khelwood
    Nov 20 at 10:15










  • Check the file name correctly, we don't usually need to escape/handle comma names in the file name or any parameter string.
    – Shariq
    Nov 20 at 10:18










  • Are you sure your path Z:\groups exists ?
    – Dinko Pehar
    Nov 20 at 10:21










  • I'm sure the path exists. Other files from the same directory are parsed without issues. Directly from the commandline, trying to open the file also gives: The system cannot find the path specified. Also, I seem to be unable to rename the file, if I try to change the name through Windows File Explorer to remove the comma (or change something else), it is reset to the original filename.
    – Phantom
    Nov 20 at 10:27
















  • 3




    I cannot reproduce this behavior with Python 3.6.3. Can you show where the variable filepath is set?
    – elzell
    Nov 20 at 10:14






  • 1




    Maybe if you use listdir on the directory you can see what the file is actually called.
    – khelwood
    Nov 20 at 10:15










  • Check the file name correctly, we don't usually need to escape/handle comma names in the file name or any parameter string.
    – Shariq
    Nov 20 at 10:18










  • Are you sure your path Z:\groups exists ?
    – Dinko Pehar
    Nov 20 at 10:21










  • I'm sure the path exists. Other files from the same directory are parsed without issues. Directly from the commandline, trying to open the file also gives: The system cannot find the path specified. Also, I seem to be unable to rename the file, if I try to change the name through Windows File Explorer to remove the comma (or change something else), it is reset to the original filename.
    – Phantom
    Nov 20 at 10:27










3




3




I cannot reproduce this behavior with Python 3.6.3. Can you show where the variable filepath is set?
– elzell
Nov 20 at 10:14




I cannot reproduce this behavior with Python 3.6.3. Can you show where the variable filepath is set?
– elzell
Nov 20 at 10:14




1




1




Maybe if you use listdir on the directory you can see what the file is actually called.
– khelwood
Nov 20 at 10:15




Maybe if you use listdir on the directory you can see what the file is actually called.
– khelwood
Nov 20 at 10:15












Check the file name correctly, we don't usually need to escape/handle comma names in the file name or any parameter string.
– Shariq
Nov 20 at 10:18




Check the file name correctly, we don't usually need to escape/handle comma names in the file name or any parameter string.
– Shariq
Nov 20 at 10:18












Are you sure your path Z:\groups exists ?
– Dinko Pehar
Nov 20 at 10:21




Are you sure your path Z:\groups exists ?
– Dinko Pehar
Nov 20 at 10:21












I'm sure the path exists. Other files from the same directory are parsed without issues. Directly from the commandline, trying to open the file also gives: The system cannot find the path specified. Also, I seem to be unable to rename the file, if I try to change the name through Windows File Explorer to remove the comma (or change something else), it is reset to the original filename.
– Phantom
Nov 20 at 10:27






I'm sure the path exists. Other files from the same directory are parsed without issues. Directly from the commandline, trying to open the file also gives: The system cannot find the path specified. Also, I seem to be unable to rename the file, if I try to change the name through Windows File Explorer to remove the comma (or change something else), it is reset to the original filename.
– Phantom
Nov 20 at 10:27














2 Answers
2






active

oldest

votes

















up vote
0
down vote



accepted










This works fine on Python 3, Windows 10



import glob, re
for filepath in glob.iglob('C:/Users/test-ABC/Desktop/test/' + r'****.*', recursive=True):
with open(filepath) as f:
print(f)
for line in f:
print(line)
for word in re.findall(r'w+', line):
pass

<_io.TextIOWrapper
name='C:/Users/test-ABC/Desktop/test\loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong
name\another
looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong
name\test, file, name.txt' mode='r' encoding='cp1251'>

line1
line2
line3


May be the problem in the long path. Try to check questions like this:
Long paths in Python on Windows






share|improve this answer





















  • The manifest of Python 3.6+ supports long paths, so if you have "LongPathsEnabled" set in "HKLMSystemCurrentControlSetControlFileSystem" in Windows 10, then normalized DOS paths support the native limit of up to about 32760 characters. Otherwise normalized DOS paths use the legacy limit of MAX_PATH (260) characters, and longer paths require an extended local-device path, which is prefixed with "\?" (or "\?UNC" for UNC) and must be fully qualified (i.e. not relative) and Unicode.
    – eryksun
    Nov 20 at 22:05










  • Thank you @eryksun. Will note that.
    – VictorDDT
    Nov 21 at 21:59










  • Thank you! It turned out that the path was too long, indeed. The comma threw me off. I'll have to look in to how best to support the long path. Thanks @eryksun for the suggestion, I'll see if that works.
    – Phantom
    Dec 6 at 11:49


















up vote
0
down vote













First, you only work on files, not directories, and second, you can use os.path.join to convert on Windows:



>>>os.path.join("d:ss")
'd:\ss'


Try this:



    from pathlib import Path
import os
import re
pathName='./'# r'd:/xx' on windows
fnLst=list(filter(lambda x:not x.is_dir(),Path(pathName).glob('**/*.txt')))
print(fnLst)
for fn in fnLst:
with open(fn) as f:
print()
print(fn)
for line in f:
for word in re.findall(r'w+', line):
print(word,end="|")


Output:



[PosixPath('2.txt'), PosixPath('1.txt')]


2.txt
This|tutorial|introduces|the|reader|informally|to|the|basic|concepts|and|features|of|the|Python|language|and|system|It|helps|to|have|a|Python|interpreter|handy|for|hands|on|experience|but|all|examples|are|self|contained|so|the|tutorial|can|be|read|off|line|as|well|
1.txt
Python|is|an|easy|to|learn|powerful|programming|language|It|has|efficient|high|level|data|structures|and|a|simple|but|effective|approach|to|object|oriented|programming|Python|s|elegant|syntax|and|dynamic|typing|together|with|its|interpreted|nature|make|it|an|ideal|language|for|scripting|and|rapid|application|development|in|many|areas|on|most|platforms|





share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53390663%2fpython-open-function-cannot-read-file%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    0
    down vote



    accepted










    This works fine on Python 3, Windows 10



    import glob, re
    for filepath in glob.iglob('C:/Users/test-ABC/Desktop/test/' + r'****.*', recursive=True):
    with open(filepath) as f:
    print(f)
    for line in f:
    print(line)
    for word in re.findall(r'w+', line):
    pass

    <_io.TextIOWrapper
    name='C:/Users/test-ABC/Desktop/test\loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong
    name\another
    looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong
    name\test, file, name.txt' mode='r' encoding='cp1251'>

    line1
    line2
    line3


    May be the problem in the long path. Try to check questions like this:
    Long paths in Python on Windows






    share|improve this answer





















    • The manifest of Python 3.6+ supports long paths, so if you have "LongPathsEnabled" set in "HKLMSystemCurrentControlSetControlFileSystem" in Windows 10, then normalized DOS paths support the native limit of up to about 32760 characters. Otherwise normalized DOS paths use the legacy limit of MAX_PATH (260) characters, and longer paths require an extended local-device path, which is prefixed with "\?" (or "\?UNC" for UNC) and must be fully qualified (i.e. not relative) and Unicode.
      – eryksun
      Nov 20 at 22:05










    • Thank you @eryksun. Will note that.
      – VictorDDT
      Nov 21 at 21:59










    • Thank you! It turned out that the path was too long, indeed. The comma threw me off. I'll have to look in to how best to support the long path. Thanks @eryksun for the suggestion, I'll see if that works.
      – Phantom
      Dec 6 at 11:49















    up vote
    0
    down vote



    accepted










    This works fine on Python 3, Windows 10



    import glob, re
    for filepath in glob.iglob('C:/Users/test-ABC/Desktop/test/' + r'****.*', recursive=True):
    with open(filepath) as f:
    print(f)
    for line in f:
    print(line)
    for word in re.findall(r'w+', line):
    pass

    <_io.TextIOWrapper
    name='C:/Users/test-ABC/Desktop/test\loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong
    name\another
    looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong
    name\test, file, name.txt' mode='r' encoding='cp1251'>

    line1
    line2
    line3


    May be the problem in the long path. Try to check questions like this:
    Long paths in Python on Windows






    share|improve this answer





















    • The manifest of Python 3.6+ supports long paths, so if you have "LongPathsEnabled" set in "HKLMSystemCurrentControlSetControlFileSystem" in Windows 10, then normalized DOS paths support the native limit of up to about 32760 characters. Otherwise normalized DOS paths use the legacy limit of MAX_PATH (260) characters, and longer paths require an extended local-device path, which is prefixed with "\?" (or "\?UNC" for UNC) and must be fully qualified (i.e. not relative) and Unicode.
      – eryksun
      Nov 20 at 22:05










    • Thank you @eryksun. Will note that.
      – VictorDDT
      Nov 21 at 21:59










    • Thank you! It turned out that the path was too long, indeed. The comma threw me off. I'll have to look in to how best to support the long path. Thanks @eryksun for the suggestion, I'll see if that works.
      – Phantom
      Dec 6 at 11:49













    up vote
    0
    down vote



    accepted







    up vote
    0
    down vote



    accepted






    This works fine on Python 3, Windows 10



    import glob, re
    for filepath in glob.iglob('C:/Users/test-ABC/Desktop/test/' + r'****.*', recursive=True):
    with open(filepath) as f:
    print(f)
    for line in f:
    print(line)
    for word in re.findall(r'w+', line):
    pass

    <_io.TextIOWrapper
    name='C:/Users/test-ABC/Desktop/test\loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong
    name\another
    looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong
    name\test, file, name.txt' mode='r' encoding='cp1251'>

    line1
    line2
    line3


    May be the problem in the long path. Try to check questions like this:
    Long paths in Python on Windows






    share|improve this answer












    This works fine on Python 3, Windows 10



    import glob, re
    for filepath in glob.iglob('C:/Users/test-ABC/Desktop/test/' + r'****.*', recursive=True):
    with open(filepath) as f:
    print(f)
    for line in f:
    print(line)
    for word in re.findall(r'w+', line):
    pass

    <_io.TextIOWrapper
    name='C:/Users/test-ABC/Desktop/test\loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong
    name\another
    looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong
    name\test, file, name.txt' mode='r' encoding='cp1251'>

    line1
    line2
    line3


    May be the problem in the long path. Try to check questions like this:
    Long paths in Python on Windows







    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Nov 20 at 11:06









    VictorDDT

    376




    376












    • The manifest of Python 3.6+ supports long paths, so if you have "LongPathsEnabled" set in "HKLMSystemCurrentControlSetControlFileSystem" in Windows 10, then normalized DOS paths support the native limit of up to about 32760 characters. Otherwise normalized DOS paths use the legacy limit of MAX_PATH (260) characters, and longer paths require an extended local-device path, which is prefixed with "\?" (or "\?UNC" for UNC) and must be fully qualified (i.e. not relative) and Unicode.
      – eryksun
      Nov 20 at 22:05










    • Thank you @eryksun. Will note that.
      – VictorDDT
      Nov 21 at 21:59










    • Thank you! It turned out that the path was too long, indeed. The comma threw me off. I'll have to look in to how best to support the long path. Thanks @eryksun for the suggestion, I'll see if that works.
      – Phantom
      Dec 6 at 11:49


















    • The manifest of Python 3.6+ supports long paths, so if you have "LongPathsEnabled" set in "HKLMSystemCurrentControlSetControlFileSystem" in Windows 10, then normalized DOS paths support the native limit of up to about 32760 characters. Otherwise normalized DOS paths use the legacy limit of MAX_PATH (260) characters, and longer paths require an extended local-device path, which is prefixed with "\?" (or "\?UNC" for UNC) and must be fully qualified (i.e. not relative) and Unicode.
      – eryksun
      Nov 20 at 22:05










    • Thank you @eryksun. Will note that.
      – VictorDDT
      Nov 21 at 21:59










    • Thank you! It turned out that the path was too long, indeed. The comma threw me off. I'll have to look in to how best to support the long path. Thanks @eryksun for the suggestion, I'll see if that works.
      – Phantom
      Dec 6 at 11:49
















    The manifest of Python 3.6+ supports long paths, so if you have "LongPathsEnabled" set in "HKLMSystemCurrentControlSetControlFileSystem" in Windows 10, then normalized DOS paths support the native limit of up to about 32760 characters. Otherwise normalized DOS paths use the legacy limit of MAX_PATH (260) characters, and longer paths require an extended local-device path, which is prefixed with "\?" (or "\?UNC" for UNC) and must be fully qualified (i.e. not relative) and Unicode.
    – eryksun
    Nov 20 at 22:05




    The manifest of Python 3.6+ supports long paths, so if you have "LongPathsEnabled" set in "HKLMSystemCurrentControlSetControlFileSystem" in Windows 10, then normalized DOS paths support the native limit of up to about 32760 characters. Otherwise normalized DOS paths use the legacy limit of MAX_PATH (260) characters, and longer paths require an extended local-device path, which is prefixed with "\?" (or "\?UNC" for UNC) and must be fully qualified (i.e. not relative) and Unicode.
    – eryksun
    Nov 20 at 22:05












    Thank you @eryksun. Will note that.
    – VictorDDT
    Nov 21 at 21:59




    Thank you @eryksun. Will note that.
    – VictorDDT
    Nov 21 at 21:59












    Thank you! It turned out that the path was too long, indeed. The comma threw me off. I'll have to look in to how best to support the long path. Thanks @eryksun for the suggestion, I'll see if that works.
    – Phantom
    Dec 6 at 11:49




    Thank you! It turned out that the path was too long, indeed. The comma threw me off. I'll have to look in to how best to support the long path. Thanks @eryksun for the suggestion, I'll see if that works.
    – Phantom
    Dec 6 at 11:49












    up vote
    0
    down vote













    First, you only work on files, not directories, and second, you can use os.path.join to convert on Windows:



    >>>os.path.join("d:ss")
    'd:\ss'


    Try this:



        from pathlib import Path
    import os
    import re
    pathName='./'# r'd:/xx' on windows
    fnLst=list(filter(lambda x:not x.is_dir(),Path(pathName).glob('**/*.txt')))
    print(fnLst)
    for fn in fnLst:
    with open(fn) as f:
    print()
    print(fn)
    for line in f:
    for word in re.findall(r'w+', line):
    print(word,end="|")


    Output:



    [PosixPath('2.txt'), PosixPath('1.txt')]


    2.txt
    This|tutorial|introduces|the|reader|informally|to|the|basic|concepts|and|features|of|the|Python|language|and|system|It|helps|to|have|a|Python|interpreter|handy|for|hands|on|experience|but|all|examples|are|self|contained|so|the|tutorial|can|be|read|off|line|as|well|
    1.txt
    Python|is|an|easy|to|learn|powerful|programming|language|It|has|efficient|high|level|data|structures|and|a|simple|but|effective|approach|to|object|oriented|programming|Python|s|elegant|syntax|and|dynamic|typing|together|with|its|interpreted|nature|make|it|an|ideal|language|for|scripting|and|rapid|application|development|in|many|areas|on|most|platforms|





    share|improve this answer



























      up vote
      0
      down vote













      First, you only work on files, not directories, and second, you can use os.path.join to convert on Windows:



      >>>os.path.join("d:ss")
      'd:\ss'


      Try this:



          from pathlib import Path
      import os
      import re
      pathName='./'# r'd:/xx' on windows
      fnLst=list(filter(lambda x:not x.is_dir(),Path(pathName).glob('**/*.txt')))
      print(fnLst)
      for fn in fnLst:
      with open(fn) as f:
      print()
      print(fn)
      for line in f:
      for word in re.findall(r'w+', line):
      print(word,end="|")


      Output:



      [PosixPath('2.txt'), PosixPath('1.txt')]


      2.txt
      This|tutorial|introduces|the|reader|informally|to|the|basic|concepts|and|features|of|the|Python|language|and|system|It|helps|to|have|a|Python|interpreter|handy|for|hands|on|experience|but|all|examples|are|self|contained|so|the|tutorial|can|be|read|off|line|as|well|
      1.txt
      Python|is|an|easy|to|learn|powerful|programming|language|It|has|efficient|high|level|data|structures|and|a|simple|but|effective|approach|to|object|oriented|programming|Python|s|elegant|syntax|and|dynamic|typing|together|with|its|interpreted|nature|make|it|an|ideal|language|for|scripting|and|rapid|application|development|in|many|areas|on|most|platforms|





      share|improve this answer

























        up vote
        0
        down vote










        up vote
        0
        down vote









        First, you only work on files, not directories, and second, you can use os.path.join to convert on Windows:



        >>>os.path.join("d:ss")
        'd:\ss'


        Try this:



            from pathlib import Path
        import os
        import re
        pathName='./'# r'd:/xx' on windows
        fnLst=list(filter(lambda x:not x.is_dir(),Path(pathName).glob('**/*.txt')))
        print(fnLst)
        for fn in fnLst:
        with open(fn) as f:
        print()
        print(fn)
        for line in f:
        for word in re.findall(r'w+', line):
        print(word,end="|")


        Output:



        [PosixPath('2.txt'), PosixPath('1.txt')]


        2.txt
        This|tutorial|introduces|the|reader|informally|to|the|basic|concepts|and|features|of|the|Python|language|and|system|It|helps|to|have|a|Python|interpreter|handy|for|hands|on|experience|but|all|examples|are|self|contained|so|the|tutorial|can|be|read|off|line|as|well|
        1.txt
        Python|is|an|easy|to|learn|powerful|programming|language|It|has|efficient|high|level|data|structures|and|a|simple|but|effective|approach|to|object|oriented|programming|Python|s|elegant|syntax|and|dynamic|typing|together|with|its|interpreted|nature|make|it|an|ideal|language|for|scripting|and|rapid|application|development|in|many|areas|on|most|platforms|





        share|improve this answer














        First, you only work on files, not directories, and second, you can use os.path.join to convert on Windows:



        >>>os.path.join("d:ss")
        'd:\ss'


        Try this:



            from pathlib import Path
        import os
        import re
        pathName='./'# r'd:/xx' on windows
        fnLst=list(filter(lambda x:not x.is_dir(),Path(pathName).glob('**/*.txt')))
        print(fnLst)
        for fn in fnLst:
        with open(fn) as f:
        print()
        print(fn)
        for line in f:
        for word in re.findall(r'w+', line):
        print(word,end="|")


        Output:



        [PosixPath('2.txt'), PosixPath('1.txt')]


        2.txt
        This|tutorial|introduces|the|reader|informally|to|the|basic|concepts|and|features|of|the|Python|language|and|system|It|helps|to|have|a|Python|interpreter|handy|for|hands|on|experience|but|all|examples|are|self|contained|so|the|tutorial|can|be|read|off|line|as|well|
        1.txt
        Python|is|an|easy|to|learn|powerful|programming|language|It|has|efficient|high|level|data|structures|and|a|simple|but|effective|approach|to|object|oriented|programming|Python|s|elegant|syntax|and|dynamic|typing|together|with|its|interpreted|nature|make|it|an|ideal|language|for|scripting|and|rapid|application|development|in|many|areas|on|most|platforms|






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Nov 20 at 11:29

























        answered Nov 20 at 11:12









        myhaspldeep

        16017




        16017






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.





            Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


            Please pay close attention to the following guidance:


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53390663%2fpython-open-function-cannot-read-file%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            404 Error Contact Form 7 ajax form submitting

            How to know if a Active Directory user can login interactively

            TypeError: fit_transform() missing 1 required positional argument: 'X'