-3

This is probably a stretch. I have a def (or function) that takes a file name, opens the file and performs action on the file content. Is there a way in Python to use a variable in place of the file name? In other words give a string or list file attributes.

def Albert(fname):
    f = open(fname, 'r')
    for i in f.readline():
        print(i)
#Main
Collins = 'Blues Guitar\n'
Albert(Collins)
brett
  • 198
  • 3
  • 9
  • 1
    Why would it be a stretch? That's exactly how it works. Your only problem is that your `Collins` string has a newline in it, which is not valid in a filename. – Martijn Pieters May 03 '14 at 15:19
  • But 'Collins' is not a file name, it is a string that contains 'Blues Guitar\n'. I would like the contents of the variable 'Collins' treated as the contents of a file. I'm having trouble expressing this. – brett May 03 '14 at 15:26
  • 1
    You want an in-memory file object with the *contents* being dictated by the variable. You did indeed not make that clear. In that case your question is a dupe of [Using Python, how do I to read/write data in memory like I would with a file?](http://stackoverflow.com/q/1883326) – Martijn Pieters May 03 '14 at 15:27
  • If you simply want to iterate over all lines in the String there is no need to use `StringIO` as recommended by the linked question. Just use `mystring.split("\n")` to get a list of the lines in the String, and iterate over that list. – l4mpi May 03 '14 at 15:56

1 Answers1

-1

Thanks Martijn. I will have to move f = open(fname, 'r') outside of Albert(fname) -

def Albert(fname):

    while True:
        onechar = fname.read()
        if not onechar:
            break
        else:
            print(onechar, end = '')
    print()

#Main
import io

#stringIO mode
Collins = io.StringIO('Blues Guitar')
Albert(Collins)

#fileIO mode
fname = open('infile.txt', 'r')
Albert(fname) #where infile.txt containes 'Blues Guitar'

#Output
Blues Guitar 
Blues Guitar

But that goes a long way and prevents rewriting my actual def!

brett
  • 198
  • 3
  • 9
  • Remove the `.readlines()`. It reads the file into memory first which is not neccessary. (The difference would be visible only with huge files.) You can also test the type and/or the attributes of the passed `fname` and decide whether to `open` it inside the function, or whether to wrap it into `io.StringIO`. – pepr May 04 '14 at 10:20
  • Your right. I changed fname.readlines() to fname.getvalue(). fname is of type string. – brett May 04 '14 at 14:25
  • More code added to show basic idea. – brett May 04 '14 at 14:51