How to use a variable as part of a filename - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: How to use a variable as part of a filename (/thread-23305.html) Pages:
1
2
|
How to use a variable as part of a filename - handyguy - Dec-21-2019 I would like to simplify the following code, replacing the multiple if/elif's with a single line, but I have not been able to successfully figure it out. def print_time(): now = datetime.datetime.now() hour = now.hour minute = now.minute second = now.second if hour == 1: command = 'echo 0 | fbink -i 1.png -g x=100 -c' elif hour == 2: command = 'echo 0 | fbink -i 2.png -g x=100 -c' elif hour == 3: command = 'echo 0 | fbink -i 3.png -g x=100 -c' elif hour == 4: command = 'echo 0 | fbink -i 4.png -g x=100 -c' elif hour == 5: command = 'echo 0 | fbink -i 5.png -g x=100 -c' elif hour ==6: command = 'echo 0 | fbink -i 6.png -g x=100 -c' # etc... os.system(command)Any help is much appreciated! RE: How to use a variable as part of a filename - ichabod801 - Dec-21-2019 The modern way to do it (f-string syntax): command = f'echo 0 | fbink -i {hour}.png -g x=100 -c'The backward compatible (to 3.5 and earlier) way to do it (the format method of strings): command = 'echo 0 | fbink -i {}.png -g x = 100 -c'.format(hour) RE: How to use a variable as part of a filename - handyguy - Dec-21-2019 Thanks! My code looks much better now. RE: How to use a variable as part of a filename - buran - Dec-21-2019 and also subprocess.run is preferd over os.system RE: How to use a variable as part of a filename - handyguy - Dec-24-2019 That's working well,however when there is more text following the braces, it is ignored. For example: command = 'fbink -t regular=/mnt/us/clock/bahnschrift.ttf,top=1410,px=35,format "BATTERY {}%" -me'.format(batpercent) The % (or any other text) is not displayed. ? RE: How to use a variable as part of a filename - ichabod801 - Dec-24-2019 I don't know, it's working fine for me. What is the value of batpercent? It's not a string with a new line character in it, is it? RE: How to use a variable as part of a filename - handyguy - Dec-24-2019 no, it's an integer... RE: How to use a variable as part of a filename - handyguy - Dec-26-2019 Turns out I was incorrect; it was a string with a trailing LF. RE: How to use a variable as part of a filename - handyguy - Dec-28-2019 (Dec-21-2019, 09:24 AM)buran Wrote: and also subprocess.run is preferd over os.system I am running on python v2.7; subprocess.run is not available. Would subprocess.Popen also be preferred? RE: How to use a variable as part of a filename - ichabod801 - Dec-28-2019 End of life (support) for Python 2.7 is this coming Wednesday. Switch to Python 3.x if at all possible. |