reading files from a folder using os moduleReading binary file and looping over each byteCalling a function of a module by using its name (a string)How do I check whether a file exists without exceptions?How do I copy a file in Python?Importing modules from parent folderHow do you read from stdin?How do I list all files of a directory?How to read a file line-by-line into a list?Importing files from different folderDelete a file or folderWhy is reading lines from stdin much slower in C++ than Python?

Past participle agreement with the subject in the case of pronominal verbs

How certain is a caster of when their spell will end?

PhD student with mental health issues and bad performance

Is the decompression of compressed and encrypted data without decryption also theoretically impossible?

You've spoiled/damaged the card

Does any lore text explain why the planes of Acheron, Gehenna, and Carceri are the alignment they are?

Is it OK to bring delicacies from hometown as tokens of gratitude for an out-of-town interview?

Personalization conditions switching doesn`t work in Experience Editor (9.1.0, Initial Release)

Accidentally renamed tar.gz file to a non tar.gz file, will my file be messed up

Responsibility for visa checking

Company is asking me to work from overseas, but wants me to take a paycut

Who operates delivery flights for commercial airlines?

Traffic law UK, pedestrians

Does resistor placement change power dissipation in simple LED circuit?

How could a possessed body begin to rot and decay while it is still alive?

What flavor of zksnark in tezos

Short story written from alien perspective with this line: "It's too bright to look at, so they don't"

Word for a small burst of laughter that can't be held back

Count line of code for Javascript project

Pros and cons of writing a book review?

How bad would a partial hash leak be, realistically?

Chopin: marche funèbre bar 15 impossible place

Linux tr to convert vertical text to horizontal

I completed a difficult task using a tool I developed before joining my employer. What is my obligation?



reading files from a folder using os module


Reading binary file and looping over each byteCalling a function of a module by using its name (a string)How do I check whether a file exists without exceptions?How do I copy a file in Python?Importing modules from parent folderHow do you read from stdin?How do I list all files of a directory?How to read a file line-by-line into a list?Importing files from different folderDelete a file or folderWhy is reading lines from stdin much slower in C++ than Python?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








1















for a pattern recognition application, I want to read and operate on jpeg files from another folder using the os module.



I tried to use str(file) and file.encode('latin-1') but they both give me errors



I tried :



allLines = []

path = 'results/'
fileList = os.listdir(path)
for file in fileList:
file = open(os.path.join('results/'+ str(file.encode('latin-1'))), 'r')
allLines.append(file.read())
print(allLines)


but I get an error saying:
No such file or directory "results/b'thefilename"



when I expect a list with the desired file names that are accessible










share|improve this question

















  • 1





    Your use of os.path.join is not how it's intended. You're doing the join yourself with string concatenation rather than passing it a relative path

    – roganjosh
    Mar 24 at 13:30











  • Try file = open('results/'.format(file)) in your for loop

    – roganjosh
    Mar 24 at 13:32











  • You can’t treat jpeg files as text files that have lines. (And please close() your files!)

    – Jens
    Mar 24 at 13:33












  • You can read from this documentation

    – Yusufsn
    Mar 24 at 13:34











  • file = open('results/'.format(file)) gives me utf-8 error even now

    – Mr. Johnny Doe
    Mar 24 at 13:38

















1















for a pattern recognition application, I want to read and operate on jpeg files from another folder using the os module.



I tried to use str(file) and file.encode('latin-1') but they both give me errors



I tried :



allLines = []

path = 'results/'
fileList = os.listdir(path)
for file in fileList:
file = open(os.path.join('results/'+ str(file.encode('latin-1'))), 'r')
allLines.append(file.read())
print(allLines)


but I get an error saying:
No such file or directory "results/b'thefilename"



when I expect a list with the desired file names that are accessible










share|improve this question

















  • 1





    Your use of os.path.join is not how it's intended. You're doing the join yourself with string concatenation rather than passing it a relative path

    – roganjosh
    Mar 24 at 13:30











  • Try file = open('results/'.format(file)) in your for loop

    – roganjosh
    Mar 24 at 13:32











  • You can’t treat jpeg files as text files that have lines. (And please close() your files!)

    – Jens
    Mar 24 at 13:33












  • You can read from this documentation

    – Yusufsn
    Mar 24 at 13:34











  • file = open('results/'.format(file)) gives me utf-8 error even now

    – Mr. Johnny Doe
    Mar 24 at 13:38













1












1








1








for a pattern recognition application, I want to read and operate on jpeg files from another folder using the os module.



I tried to use str(file) and file.encode('latin-1') but they both give me errors



I tried :



allLines = []

path = 'results/'
fileList = os.listdir(path)
for file in fileList:
file = open(os.path.join('results/'+ str(file.encode('latin-1'))), 'r')
allLines.append(file.read())
print(allLines)


but I get an error saying:
No such file or directory "results/b'thefilename"



when I expect a list with the desired file names that are accessible










share|improve this question














for a pattern recognition application, I want to read and operate on jpeg files from another folder using the os module.



I tried to use str(file) and file.encode('latin-1') but they both give me errors



I tried :



allLines = []

path = 'results/'
fileList = os.listdir(path)
for file in fileList:
file = open(os.path.join('results/'+ str(file.encode('latin-1'))), 'r')
allLines.append(file.read())
print(allLines)


but I get an error saying:
No such file or directory "results/b'thefilename"



when I expect a list with the desired file names that are accessible







python






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 24 at 13:28









Mr. Johnny DoeMr. Johnny Doe

62




62







  • 1





    Your use of os.path.join is not how it's intended. You're doing the join yourself with string concatenation rather than passing it a relative path

    – roganjosh
    Mar 24 at 13:30











  • Try file = open('results/'.format(file)) in your for loop

    – roganjosh
    Mar 24 at 13:32











  • You can’t treat jpeg files as text files that have lines. (And please close() your files!)

    – Jens
    Mar 24 at 13:33












  • You can read from this documentation

    – Yusufsn
    Mar 24 at 13:34











  • file = open('results/'.format(file)) gives me utf-8 error even now

    – Mr. Johnny Doe
    Mar 24 at 13:38












  • 1





    Your use of os.path.join is not how it's intended. You're doing the join yourself with string concatenation rather than passing it a relative path

    – roganjosh
    Mar 24 at 13:30











  • Try file = open('results/'.format(file)) in your for loop

    – roganjosh
    Mar 24 at 13:32











  • You can’t treat jpeg files as text files that have lines. (And please close() your files!)

    – Jens
    Mar 24 at 13:33












  • You can read from this documentation

    – Yusufsn
    Mar 24 at 13:34











  • file = open('results/'.format(file)) gives me utf-8 error even now

    – Mr. Johnny Doe
    Mar 24 at 13:38







1




1





Your use of os.path.join is not how it's intended. You're doing the join yourself with string concatenation rather than passing it a relative path

– roganjosh
Mar 24 at 13:30





Your use of os.path.join is not how it's intended. You're doing the join yourself with string concatenation rather than passing it a relative path

– roganjosh
Mar 24 at 13:30













Try file = open('results/'.format(file)) in your for loop

– roganjosh
Mar 24 at 13:32





Try file = open('results/'.format(file)) in your for loop

– roganjosh
Mar 24 at 13:32













You can’t treat jpeg files as text files that have lines. (And please close() your files!)

– Jens
Mar 24 at 13:33






You can’t treat jpeg files as text files that have lines. (And please close() your files!)

– Jens
Mar 24 at 13:33














You can read from this documentation

– Yusufsn
Mar 24 at 13:34





You can read from this documentation

– Yusufsn
Mar 24 at 13:34













file = open('results/'.format(file)) gives me utf-8 error even now

– Mr. Johnny Doe
Mar 24 at 13:38





file = open('results/'.format(file)) gives me utf-8 error even now

– Mr. Johnny Doe
Mar 24 at 13:38












1 Answer
1






active

oldest

votes


















1














If you can use Python 3.4 or newer, you can use the pathlib module to handle the paths.



from pathlib import Path

all_lines = []
path = Path('results/')
for file in path.iterdir():
with file.open() as f:
all_lines.append(f.read())
print(all_lines)


By using the with statement, you don't have to close the file descriptor by hand (what is currently missing), even if an exception is raised at some point.






share|improve this answer























  • still getting an error saying all_lines.append(f.read()) UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte

    – Mr. Johnny Doe
    Mar 24 at 14:12







  • 1





    Yes, because someone wrote to you before you use binary data (.jpeg) and they have nothing to do with UTF-8 or another text encoding. These are bytes. You must not understand it as lines, not as text at all. First, you have to determine that this is a binary data f = open("myfile", "rb") and secondly you have to work with the buffer if you want to read the data sequentially. For example: stackoverflow.com/questions/1035340/…

    – s3n0
    Mar 24 at 14:18












  • If you actually want to read binary, you can read with 'rb' mode. with file.open('rb') as f:

    – Querenker
    Mar 24 at 14:19












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',
autoActivateHeartbeat: false,
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%2f55324275%2freading-files-from-a-folder-using-os-module%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









1














If you can use Python 3.4 or newer, you can use the pathlib module to handle the paths.



from pathlib import Path

all_lines = []
path = Path('results/')
for file in path.iterdir():
with file.open() as f:
all_lines.append(f.read())
print(all_lines)


By using the with statement, you don't have to close the file descriptor by hand (what is currently missing), even if an exception is raised at some point.






share|improve this answer























  • still getting an error saying all_lines.append(f.read()) UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte

    – Mr. Johnny Doe
    Mar 24 at 14:12







  • 1





    Yes, because someone wrote to you before you use binary data (.jpeg) and they have nothing to do with UTF-8 or another text encoding. These are bytes. You must not understand it as lines, not as text at all. First, you have to determine that this is a binary data f = open("myfile", "rb") and secondly you have to work with the buffer if you want to read the data sequentially. For example: stackoverflow.com/questions/1035340/…

    – s3n0
    Mar 24 at 14:18












  • If you actually want to read binary, you can read with 'rb' mode. with file.open('rb') as f:

    – Querenker
    Mar 24 at 14:19
















1














If you can use Python 3.4 or newer, you can use the pathlib module to handle the paths.



from pathlib import Path

all_lines = []
path = Path('results/')
for file in path.iterdir():
with file.open() as f:
all_lines.append(f.read())
print(all_lines)


By using the with statement, you don't have to close the file descriptor by hand (what is currently missing), even if an exception is raised at some point.






share|improve this answer























  • still getting an error saying all_lines.append(f.read()) UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte

    – Mr. Johnny Doe
    Mar 24 at 14:12







  • 1





    Yes, because someone wrote to you before you use binary data (.jpeg) and they have nothing to do with UTF-8 or another text encoding. These are bytes. You must not understand it as lines, not as text at all. First, you have to determine that this is a binary data f = open("myfile", "rb") and secondly you have to work with the buffer if you want to read the data sequentially. For example: stackoverflow.com/questions/1035340/…

    – s3n0
    Mar 24 at 14:18












  • If you actually want to read binary, you can read with 'rb' mode. with file.open('rb') as f:

    – Querenker
    Mar 24 at 14:19














1












1








1







If you can use Python 3.4 or newer, you can use the pathlib module to handle the paths.



from pathlib import Path

all_lines = []
path = Path('results/')
for file in path.iterdir():
with file.open() as f:
all_lines.append(f.read())
print(all_lines)


By using the with statement, you don't have to close the file descriptor by hand (what is currently missing), even if an exception is raised at some point.






share|improve this answer













If you can use Python 3.4 or newer, you can use the pathlib module to handle the paths.



from pathlib import Path

all_lines = []
path = Path('results/')
for file in path.iterdir():
with file.open() as f:
all_lines.append(f.read())
print(all_lines)


By using the with statement, you don't have to close the file descriptor by hand (what is currently missing), even if an exception is raised at some point.







share|improve this answer












share|improve this answer



share|improve this answer










answered Mar 24 at 13:52









QuerenkerQuerenker

1,041919




1,041919












  • still getting an error saying all_lines.append(f.read()) UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte

    – Mr. Johnny Doe
    Mar 24 at 14:12







  • 1





    Yes, because someone wrote to you before you use binary data (.jpeg) and they have nothing to do with UTF-8 or another text encoding. These are bytes. You must not understand it as lines, not as text at all. First, you have to determine that this is a binary data f = open("myfile", "rb") and secondly you have to work with the buffer if you want to read the data sequentially. For example: stackoverflow.com/questions/1035340/…

    – s3n0
    Mar 24 at 14:18












  • If you actually want to read binary, you can read with 'rb' mode. with file.open('rb') as f:

    – Querenker
    Mar 24 at 14:19


















  • still getting an error saying all_lines.append(f.read()) UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte

    – Mr. Johnny Doe
    Mar 24 at 14:12







  • 1





    Yes, because someone wrote to you before you use binary data (.jpeg) and they have nothing to do with UTF-8 or another text encoding. These are bytes. You must not understand it as lines, not as text at all. First, you have to determine that this is a binary data f = open("myfile", "rb") and secondly you have to work with the buffer if you want to read the data sequentially. For example: stackoverflow.com/questions/1035340/…

    – s3n0
    Mar 24 at 14:18












  • If you actually want to read binary, you can read with 'rb' mode. with file.open('rb') as f:

    – Querenker
    Mar 24 at 14:19

















still getting an error saying all_lines.append(f.read()) UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte

– Mr. Johnny Doe
Mar 24 at 14:12






still getting an error saying all_lines.append(f.read()) UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte

– Mr. Johnny Doe
Mar 24 at 14:12





1




1





Yes, because someone wrote to you before you use binary data (.jpeg) and they have nothing to do with UTF-8 or another text encoding. These are bytes. You must not understand it as lines, not as text at all. First, you have to determine that this is a binary data f = open("myfile", "rb") and secondly you have to work with the buffer if you want to read the data sequentially. For example: stackoverflow.com/questions/1035340/…

– s3n0
Mar 24 at 14:18






Yes, because someone wrote to you before you use binary data (.jpeg) and they have nothing to do with UTF-8 or another text encoding. These are bytes. You must not understand it as lines, not as text at all. First, you have to determine that this is a binary data f = open("myfile", "rb") and secondly you have to work with the buffer if you want to read the data sequentially. For example: stackoverflow.com/questions/1035340/…

– s3n0
Mar 24 at 14:18














If you actually want to read binary, you can read with 'rb' mode. with file.open('rb') as f:

– Querenker
Mar 24 at 14:19






If you actually want to read binary, you can read with 'rb' mode. with file.open('rb') as f:

– Querenker
Mar 24 at 14:19




















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.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55324275%2freading-files-from-a-folder-using-os-module%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

SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

용인 삼성생명 블루밍스 목차 통계 역대 감독 선수단 응원단 경기장 같이 보기 외부 링크 둘러보기 메뉴samsungblueminx.comeh선수 명단용인 삼성생명 블루밍스용인 삼성생명 블루밍스ehsamsungblueminx.comeheheheh

155 수학 과학 기타 둘러보기 메뉴eh추가해eh문서를 완성해