Nikolay
Nikolay

Reputation: 1

Python txt file operation

I have a folder with files and want to separate the files in two variables.

For example these are the files:

EXfileone.txt
fileone.txt
EXtest.txt
simple.txt

Now the thing I can't do is this (in pseudocode):

If "EX" in filename:
    add file to variable: EXFILES

IF "EX" not in filename:
    add file to variable : NORMALFILES

So now:

EXFILES = [EXFfileone.txt, EXtest.txt]
NORMALFILES = [fileone.txt, simple.txt]

Then I will use a for loop to make operation with the files:

for file in EXFILES:
    ...

I'm using Python 3.

Upvotes: 0

Views: 102

Answers (5)

code-lukas
code-lukas

Reputation: 1651

You can also use Pythons built-in filter and lambda functions:

import os

my_list = list(filter(lambda x: 'EX' in x, os.listdir(some_dir)))
my_other_list = list(filter(lambda x: 'EX' not in x, os.listdir(some_dir)))

Will output two lists filtered with your search criterion.

Upvotes: 0

Izaak Cornelis
Izaak Cornelis

Reputation: 322

use the in operator. It checks if a string contains a sub-string:

from os import listdir

EX_files = []
NORMAL_files = []

for file_name in listdir(): 
    if "EX" in file_name:
        EX_files.append(file_name)
    else:
        NORMAL_files.append(file_name)

Upvotes: 0

Diego Palacios
Diego Palacios

Reputation: 1144

You can make each variable a list and store the names of the files in them:

from os import listdir
from os.path import isfile, join

folder_path = '/home/youruser/example' # path to folder

# classify files
exfiles = []
normalfiles= []

for f in listdir(folder_path):
    if isfile(join(folder_path, f)):
        if f.startswith('EX'):
            exfiles.append(join(folder_path, f))
        else:
            normalfiles.append(join(folder_path, f))

for fname in exfiles:
    with open(fname) as f:
        # do operations

Upvotes: 1

fabioconcina
fabioconcina

Reputation: 459

You can simply use the standard library glob module to match pathnames:

import glob


EXFILES = []
NORMALFILES = []

filename_list = glob.glob("*.txt")

for filename in filename_list:
    if "EX" in filename:
        EXFILES.append(filename)
    else:
        NORMALFILES.append(filename)

Upvotes: 3

accdias
accdias

Reputation: 5372

Try this:

from pathlib import Path

folder = Path('/path/to/your/folder')

exfiles = list(folder.glob('EX*.txt'))
normalfiles = [f for f in folder.glob('*.txt') if not f.name.startswith('EX')]

That will give you the list of files as you wanted.

But it is better do something like this instead:

from pathlib import Path

folder = Path('/path/to/your/folder')

for f in folder.glob('*.txt'):
    if f.name.startswith('EX'):
       # do something with your EX*.txt file
    else:
       # do something with your normal file

I hope it helps.

Upvotes: 2

Related Questions