2

I want to extract file names from a folder and be able to use the names as strings:

I can get the file names from the folder but they are going into a list. Ideally I do not want to iterate over the list. Code so far:

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

f = '/path/to/file/*.sql'
for files in glob.glob(f):
    with open(files, 'r',encoding = "utf-8", errors="replace") as f:
        path = "/path/to/file/folder"
        onlyTxtFiles = [f for f in listdir(path) if isfile(join(path, f)) and  f.endswith(".sql")]

not sure how to put the string of the file name into variable 'onlyTxtFiles'.

edit;

I want to be able to do this:

onlyTxtFiles = 'file name'
str1 = onlyTxtFiles + 'test'

edit:

This is a for loop I made, but I am not looping over the files:

f = '/path/to/file/sql_files/*.sql'
for files in glob.glob(f):
    with open(files, 'r',encoding = "utf-8", errors="replace") as f:
        path = "/path/to/file/sql_files/"
        onlySqlFiles = [f for f in listdir(path) if isfile(join(path, f)) and  f.endswith(".sql")]
        for x in onlySqlFiles:
            file_name_insert = x

what am I doing wrong?

RustyShackleford
  • 3,462
  • 9
  • 40
  • 81
  • 1
    I'm confused. If you have more than one file name, and you want those file names to be in one variable, why don't you want a list? Associating many values to one name is pretty much exactly what lists are for. – Kevin Jul 24 '18 at 19:02
  • @Kevin I made an edit, I am not sure how I can take the file names out so I can append them to different strings – RustyShackleford Jul 24 '18 at 19:11
  • Let's say your directory contains the files "foo", "bar", and "baz". What do you want the outcome to be? Three objects with values "footest", "bartest", and "baztest"? What would the names of those variables be? `str1`, `str2`, and `str3`? If so, you are asking for variable variables, and 99.9999% of the time, you should be using a list or dictionary instead. Related reading: [How do I create a variable number of variables?](https://stackoverflow.com/q/1373164/953482) – Kevin Jul 24 '18 at 19:14
  • _"This is a for loop I made, but I am not looping over the files: "_ Sure you are. What makes you think you aren't? If you're about to say "well, after the loop, I do `print(file_name_insert)`, and it only prints one value", then there's your problem: you should be doing that _inside_ the loop. – Kevin Jul 24 '18 at 19:43
  • @Kevin you are correct. thank you – RustyShackleford Jul 24 '18 at 19:44

1 Answers1

1

you say you want the code to be something like

onlyTxtFiles = 'file name'
str1 = onlyTxtFiles + 'test'

but if onlyTxtFiles is a list then it will return an error

one way would be to

onlyTxtFiles = 'file name'
str1 = onlyTxtFiles[0] + 'test'

for each expected value

or you could just use a for-loop