0

in python I have

title0="Blabla0"
title1="Blabla1"
title2="Blala2"
title3="Blabla3"

etc.

to write them all into a txt.file I'm specifying the path and name of file at the beginning with:

fileWrite=open('/.../final.txt','w')

and I'm calling the function

def FileWrt(typo):
fileWrite.write(typo)

after each 'title', to push the information into the file. So, my question is: Is there a way not to call FileWrt function after every 'title' or can I get rid of repeating FileWrt(title1) etc., after every title?

if I write:

FileWrt(descr,title0,title1,title2, etc.) 

at the end, can I make my FileWrt() function accept as much parameters, as sent, without specifying them every time? Otherwise it will say me that that function takes 1 argument, but n is given.

Thanks

ipsissimus
  • 51
  • 1
  • 8
  • 2
    `title0`, `title1`, ... is a common programming mistake. If you have multiple of a given item, use a data structure to contain them - here a list `titles = ["Blabla0", "Blabla1", ...]` would be appropriate. – Gareth Latty May 07 '14 at 23:16
  • https://docs.python.org/2/tutorial/controlflow.html#arbitrary-argument-lists – Natecat May 07 '14 at 23:16
  • I'm not sure what you're asking, but you can have a variable number of arguments to a method / function using `*args`, the `*` being the important part. The result will inside the method/func it is considered a `list`. – SimplyKnownAsG May 07 '14 at 23:19

2 Answers2

2

The following code will do what you want:

def FileWrt(*typos):
    for typo in typos:
        fileWrite.write(typo)

The * before typos means make a list of given arguments.

ElmoVanKielmo
  • 10,907
  • 2
  • 32
  • 46
-1

That's how you can write a function with a flexible signature.

def FileWrt(*args, **kw):
    # args is a tuple of all arg
    # kw is a dict with all named parameters
    print args, kw

In [10]: FileWrt(1, 2, 3, a = 4, b = 5)
(1, 2, 3) {'a': 4, 'b': 5}
koffein
  • 1,792
  • 13
  • 21
  • @ElmoVanKielmo: This question is a duplicate, so I don't think it serves anyone much to get upset about repeating answers. Anyone who knows about the `*args` syntax could provide the same answer, without intending to copy anyone else. – Blckknght May 07 '14 at 23:40
  • @ElmoVanKielmo Please relax, there is only one solution for multiple arguments, I was writing it at the same time and I posted it. Besides: your `typos` is a tuple, not a list. – koffein May 08 '14 at 00:31
  • @ElmoVanKielmo And yes, I added keyword arguments, because that is the next question that might pop into the OPs mind. – koffein May 08 '14 at 00:35