1

Scenario: I have a list of strings that contains multiple file names. I am trying to either create a new list with just a part of each name, or to edit the original list to have just the part I wan. For example:

Original first item of list:

"iteration5_test1_part1.txt"

Wanted result:

"iteration5"

(basically I want to keep only what comes before the first underscore)

Although I read here How to modify list entries during for loop? that it is not good practice to edit a list, I don't know any others ways to do it, so I am trying:

mypath = "/DGMS/Destop/uploaded"
from os import listdir
from os.path import isfile, join
onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))]

for f in onlyfiles:
    f = f.split("_")
    f = f[0]

But unfortunately, this does not change the list in the wanted way.

Question: What am I doing wrong?

DGMS89
  • 1,507
  • 6
  • 29
  • 60

6 Answers6

3

The for loop binds the name f to the individual strings in the list, and then your loop body simply rebinds the name. This won't affect the list at all, it simply binds the name to a new string you create and then discards it before entering the next loop iteration. I recommend reading this article by Ned Batchelder for a more in-depth explanation of how Python names and assignments work.

The easiest solution is to use a list comprehension instead:

onlyfiles = [name.split("_")[0] for name in onlyfiles]
Sven Marnach
  • 574,206
  • 118
  • 941
  • 841
2

Strings in Python are immutable, meaning they cannot be modified in-place.

You will have to re-assign the modified string to the list.

L = ["iteration5_test1_part1.txt"]

for index, item in enumerate(L):
    L[index] = item.split('_')[0]

print(L) # ['iteration5']

or as a list comprehension:

L = [item.split('_')[0] for item in L]
Mike Scotty
  • 10,530
  • 5
  • 38
  • 50
1
mypath = "/DGMS/Destop/uploaded"

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

onlyfiles = [f.split("_")[0] for f in listdir(mypath) if isfile(join(mypath, f))]    
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
1

Maybe

for i in range(len(onlyfiles)):
    temp = onlyfiles[i].split("_")[0]
    onlyfiles[i]=temp

will help.

Marcus.Aurelianus
  • 1,520
  • 10
  • 22
1

Its a simple matter of splitting the string using a delimiter.

>>> [s.split('_')[0] for s in l]

#driver values:

IN : l = ["iteration5_test1_part1.txt", "hello_world", "abc_"]
OUT : ['iteration5', 'hello', 'abc']
Kaushik NP
  • 6,733
  • 9
  • 31
  • 60
1

You can do this to create a new list

mypath = "/DGMS/Destop/uploaded"
from os import listdir
from os.path import isfile, join
onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))]
new_list = []
for f in onlyfiles:
    f = f.split("_")
    new_list.append(f[0])
sjaymj62
  • 386
  • 2
  • 18