String formation using loop and split function

Question:

I have (let´s suppose only) two file_names:

file_name1 = 'stock1'
file_name2 = 'stock2'

The code below does what we expect:

for i in range(1,3,1):
    string_name = 'file_name{}'.format(i)
    print(string_name) 

Question: how should I change the string_name line above if my initial file_names are not:

file_name1 = 'stock1'
file_name2 = 'stock2'

but they are:

file_name1 = 'stock1.split('/')'
file_name2 = 'stock2.split('/)'

where the split is there for other purposes that do not present any trouble?

Thanks!

Asked By: fskilnik

||

Answers:

If you want the filenames:-

list_containing_filenames = ['C:/Users/Documents/VALE3_daily_22May19.csv', 'C:/Users/Something/Documents/AnotherSomething/PETR4_daily_22May19.csv']

for x in list_containing_filenames:
    print(*"{}".format(x).split('/')[-1:])

OUTPUT:-

VALE3_daily_22May19.csv
PETR4_daily_22May19.csv

Add your file_path’s inside the list, and get their filenames.

If you want names of the stocks:-

list_containing_filenames = ['C:/Users/Documents/VALE3_daily_22May19.csv', 'C:/Users/Something/Documents/AnotherSomething/PETR4_daily_22May19.csv']

for x in list_containing_filenames:
    print("".join("{}".format(x).split('/')[-1:]).split("_")[0])

OUTPUT:-

VALE3
PETR4
Answered By: Vasu Deo.S

This should work to extract the text in the filename preceding the underscore:

import os
files = ['C:/Users/Documents/PETR4_daily_22May19.csv', 'C:/Users/Documents/VALE3_daily_22May19.csv']
for file in files:
    x = os.path.basename(file).split('_')[0]
    print(x)

Explanation: os.path.basename gets just the filename (without the file path), then .split('_') splits that filename on underscores, and the [0] returns the 0th (first) element of the list returned by split.

Answered By: Evan
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.