How to Name a File by a Variable Name in Python

What variable name do you use for file descriptors?

 data_file
settings_file
results_file
.... etc

Python: name folder and file with variable name

The name/name is you are trying to devide name by name. the / is not in a string but an operator.
There are two options to solve this.

  1. Make the / string

    csvfile = open(name+"/"+name+"1day.csv", 'w', newline='')

    However, this option will cause issue if you want it to run in windows and
    Linux . So the option two is an notch up.

  2. Use os.path.join()

    You have to import the os and use the the join to create a whole path.
    you script will look like the following

    import pathlib
    import csv
    import os # <--- new line

    name = input()
    pathlib.Path(name).mkdir(parents=True, exist_ok=True)
    csvfile = open(os.path.join(name, name+"1day.csv"), 'w', newline='') # <--- changed one.

    The os.path.join will ensure to use right one (/ or \) depending on the OS you are running.

Python inserting variable string as file name

You need to put % name straight after the string:

f = open('%s.csv' % name, 'wb')

The reason your code doesn't work is because you are trying to % a file, which isn't string formatting, and is also invalid.

Creating Text File with Variable as the File Name

You have to remove or replace the slash bar in:

filename = "TestFileWrite_" + today.strftime("%d/%m/%Y")

The date format should be changed, for example:

filename = "TestFileWrite_" + today.strftime("%Y%m%d")

or

filename = "TestFileWrite_" + today.strftime("%d_%m_%Y")

Moreover, the type of 'filename' is already 'str', so there is no need to use str() function:

f = open(filename+'.txt', 'w')

How do I dynamically create a variable name in a loop to assign to a file name in python 3

If you are going to use the file pointer outside this for loop, you can very well use a dictionary to do that..

def opensource():
listOfFiles = os.listdir('.')
pattern = "*.pdf"
file_ptrs = {}
for entry in listOfFiles:
if fnmatch.fnmatch(entry, pattern):
# Works to here perfectly
for i in range(len(entry)):
# print(len(entry))
# Trying to create the variable name with
# an incremental numeral in the file name
file_ptrs["pdf" + str(i) + "File"] = open(entry, 'rb')

Caution: Its always advisable to use the open method alongside of a "with" clause in python.. it takes care of closing the file once the file operation goes out of context.

Are variable names in Python valid file names?

This may vary for other OSes, but under Windows, all the reserved (forbidden) characters for file names are also not allowed within Python variable names:

  • < (less than)
  • > (greater than)
  • : (colon)
  • " (double quote)
  • / (forward slash)
  • \ (backslash)
  • | (vertical bar or pipe)
  • ? (question mark)
  • * (asterisk)

However, there are a few different problems: Certain names are not allowed as Windows file names, specifically:

CON, PRN, AUX, NUL, COM1, COM2, COM3, COM4, COM5, COM6, COM7, COM8, COM9, LPT1, LPT2, LPT3, LPT4, LPT5, LPT6, LPT7, LPT8, and LPT9

So, you can't name a file CON.txt under windows even though CON would be a perfectly valid variable name in Python.

Then, there is a length limit for filenames, so very long variable names might cause a problem.

Lastly, Python variable names may be comprised of a wide range of Unicode characters, not all of which may be available for filenames.



Related Topics



Leave a reply



Submit