arealhobo
arealhobo

Reputation: 467

Python - Add quotes to parameter in called function

Say I have a text file containing a list of file names

file name0.txt

file name1.txt

I want to pass these files names to a function

fnames = open('names.txt', 'r')

for n in fnames
     MyFunction(n)

How do I encapsulate 'n' so it passes the filenames with quotes?

Upvotes: 0

Views: 183

Answers (2)

Adirio
Adirio

Reputation: 5286

open function in Python returns a file object. This kind of objects need to be treated carefuly, as they require to be closed:

fnames = open('names.txt', 'r')
# File is open
# Do whatever you want
close(fnames)
# File is closed

The pythonic way to do this is using the with:

with open('names.txt', 'r') as fnames:
    # File is open
    # Do whatever you want
# File is closed

The with statement will close the file automatically when you get out of its indented section.

There are also different ways to read a file, iterating over a file object for example yields a row per iteration.

with open('names.txt', 'r') as fnames:
    for fname in fnames:
        print(fname)

that will yield:

file name0.txt

file name1.txt

The extra new line is because the value of fnames is "file name0.txt\n", if you want to avoid this you could do:

with open('names.txt', 'r') as fnames:
    for fname in fnames:
        print(fname.strip())

that will yield:

file name0.txt
file name1.txt

You also probably want to remove the file prefix:

prefixes = ("file",)  # Add here extra prefixes that you want to remove

with open('names.txt', 'r') as fnames:
    for fname in fnames:
        if fname.startswith(prefixes):  # There is at least one prefix to remove
            for prefix in prefixes:
                if fname.startswith(prefix):
                    fname = fname[len(prefix):]
        print(fname.strip())

that will yield:

name0.txt
name1.txt

They don't have the quotes in the console but that is because printing a string doesn't print the quotes, so you can use them to read the files:

prefixes = ("file",)  # Add here extra prefixes that you want to remove

with open('names.txt', 'r') as fnames:
    for fname in fnames:
        if fname.startswith(prefixes):  # There is at least one prefix to remove
            for prefix in prefixes:
                if fname.startswith(prefix):
                    fname = fname[len(prefix):]
        with open(fname.strip(), 'r') as f:
            # Do whatever you need with f

Upvotes: 1

CezarySzulc
CezarySzulc

Reputation: 2009

Try this:

for n in fnames
     MyFunction("'{}'".format(n))

Upvotes: 0

Related Questions