Issue
I have files named as file_1.txt,file_2.txt,file_3.txt ... till file_589.txt in a folder. I want to make a loop to read only the even numbered files and concatenate them. Concatenation is not the issue . How do we read the files ?
Solution
You can do it with the os
module.
- Change your directory to the folder conatining the files using
os.chdir()
. - List all the files in that folder using
os.listdir()
. This will give names of files in a list. - Iterate over that list and check if the filename ends with even number.
for i in os.listdir():
if int(i.split('_')[-1].split('.')[0]) % 2 == 0:
print(i)
# You can open the file and Do your concatenation here.
If you need a one-liner:
even_files = [x for x in os.listdir() if int(x.split('_')[-1].split('.')[0])%2 == 0]
Answered By - Ram
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.