Reputation:
This is my code, pinched from this site:
import os
for file in os.listdir("C:\\"):
if file.endswith(".txt"):
file = file.strip(".txt")
print(file)
It works great, but I want to be able to manipulate my results and store them into a list, and I'm not sure how to do that. It's probably super simple and missing me completely, I'm sort of a noob. Thanks :)
EDIT:
I removed the readlines part, that wasn't meant to be there. What I am trying to do is get the names of every .txt file in the folder, in this case the folder is C:\
Upvotes: 1
Views: 106
Reputation: 155734
A couple alternatives to incBrain's (perfectly fine) answer.
First, to simplify your own code instead of reinventing the wheel, use glob.glob
:
import glob
onlytxt = [file[:-4] for file in glob.glob('C:\\*.txt')]
Or to get higher performance on Python 3.5+ (or any version of Python using the scandir
module from PyPI):
import os # Pre-3.5, you'd import and use the scandir module from PyPI
# Use file.path[:-4] to store the full path (sans .txt extension)
# where file.name[:-4] only gets the file name without the path or extension
onlytxt = [file.name[:-4] for file in os.scandir('C:\\') if file.name.endswith('.txt')]
Or for true ridiculousness, push more work to the C layer and avoid redundancy by splitting off the extension once, instead of one check for it, then another operation to strip it:
import os
from operator import attrgetter
components = map(os.path.splitext, map(attrgetter('name'), os.scandir('C:\\')))
onlytxt = [root for root, ext in components if ext == 'txt']
os.scandir
doesn't do much for you in this case (you're not reading any attributes it might have checked for you), but in a largish directory, it means you aren't storing all entries at once (os.listdir
and most other APIs read the complete contents of the directory into a list
first before you have a chance to filter it), so peak memory usage is reduced when few files are matched.
Upvotes: 2
Reputation: 3784
Probably you want to have something like this:
import os
allfiles = os.listdir('C:\\')
onlytxt = [x for x in allfiles if x.endswith('.txt')]
print onlytxt
if you don't want to have .txt in the list do this:
onlytxt = [x[:-4] for x in allfiles if x.endswith('.txt')]
Upvotes: 1