0

i want to create a new .txt file every time i run the python script. Any idea how to do that . My current code :

import datetime
def write_up_commands(up_int):
    fp = open(datetime.datetime.now().strftime("20%y-%m-%d %H:%M:%S") + '_abc.txt', 'w+')
    for i in up_int:
        fp.write('int ' + i + '\n mode \n')
    fp.close()

something like

1_abc
2_abc
3_abc

can i add a date/timestamp ?

Error :

IOError: [Errno 22] invalid mode ('w+') or filename: '2018-09-10 18:02:40_abc.txt'

For user input :

def write_up_commands(up_int):
    user_text = input("write the name of the file: ")
    fp = open(datetime.datetime.now().strftime("%Y-%m-%d %H.%M.%S") + user_text + '.txt', 'w+')
    #with open(datetime.datetime.now().strftime("%Y-%m-%d %H.%M.%S") + user_text + '.txt', 'w+') as fp:
    for i in up_int:           
            fp.write('int ' + i + '\n mode \n')

NameError: name 'jinni' is not defined
Jinni
  • 21
  • 6
  • 1
    Sure you can, did you try? The quick and dirty version would just `open(date + '_abc.txt')`, where `date` is the date/time as a string. I'm sure you'll be able to find out how to get that. – timgeb Sep 10 '18 at 11:52
  • Possible duplicate https://stackoverflow.com/questions/44635896/python-logging-new-log-file-every-time-application-runs – Jorge Lavín Sep 10 '18 at 11:55
  • @JorgeLavín that question seems to be centered around using the `logging` module. – timgeb Sep 10 '18 at 11:56
  • @timgeb Yes, however the provided answers answer this question as well – Jorge Lavín Sep 10 '18 at 11:57
  • @JorgeLavín I agree, I'm hesitant to point OP to that question via goldhammer because it might be overwhelming. – timgeb Sep 10 '18 at 11:58
  • @timgeb: i tried " datetime " module but i am getting error.I updated the question. – Jinni Sep 10 '18 at 12:30
  • If you're on Windows, `:` is an invalid character in file names. – Holmes Sep 10 '18 at 12:41
  • yeah , it worked in Linux..How can i create new .txt file everytime i run the script ? – Jinni Sep 10 '18 at 12:56
  • an easy method if you do not care about the time stamp could be just add a uuid in front, that won't recuire much formating. – Jonas Wolff Sep 11 '18 at 12:31

1 Answers1

1

The error that you're reporting is caused by the : in the folder's name. Replace that with a valid character:

import datetime
def write_up_commands(up_int):
    fp = open(datetime.datetime.now().strftime("%Y-%m-%d %H.%M.%S") + '_abc.txt', 'w+')
    for i in up_int:
        fp.write('int ' + i + '\n mode \n')
    fp.close()

Let's check what is going on:
with datetime.datetime.now() we ask the time of now, so the current time
with .strftime("%Y-%m-%d %H.%M.%S") we format the time from the datetime module as we prefea: %Y means 4 digits year, then we want a -, then a two digits month %m, then -, two digits day %d, space , 24h format hours %H, dot ., 2 digits minutes %M, dot ., two digit seconds %s.
You can print the current datetime with:

print(datetime.datetime.now().strftime("%Y-%m-%d %H.%M.%S"))

with + '_abc.txt' we add at the datetime the '_abc.txt' text.
You can print the full text with:

print(datetime.datetime.now().strftime("%Y-%m-%d %H.%M.%S") + '_abc.txt')

with open('my_file.txt', 'w+') we ask our operating system to create a file with the name my_file.txt. w+ Opens a file for both writing and reading. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing.
with

for i in up_int:
    fp.write('int ' + i + '\n mode \n')
fp.close()

you write in your file 'int ' + i + '\n mode \n' for each i in up_int.

If we want to create a file with a different name, we can modify the (datetime.datetime.now().strftime("%Y-%m-%d %H.%M.%S") + '_abc.txt' line. If for example we want a file with: current date, underscore, user input, .txt we can write:

user_text = raw_input("write the name of the file: ")
fp = open(datetime.datetime.now().strftime("%Y-%m-%d %H.%M.%S") + user_text + '.txt', 'w+')
...

Even if not asked, I'd like to point out that fp.close() is the line which closes the file. It is dangerous to handle this method like that, because if you forget to close the file or something happens before the file closes, you will leave open files all around. I suggest you to change all your code with:

with open(datetime.datetime.now().strftime("%Y-%m-%d %H.%M.%S") + user_text + '.txt', 'w+') as fp:
    for i in up_int:
    fp.write('int ' + i + '\n mode \n')

which automatically handles the closing procedure in any situation.

For your second question, you actually are creating a new file each time. Keep in mind that, since the file's name changes with the time, if you create more than 1 file each second, each file will overwrite the previous one.

As a side note, notice that I've changed 20%y with %Y, which is the correct way to display the 4-digit year

Gsk
  • 2,929
  • 5
  • 22
  • 29
  • instead of generating " _abc.txt " , can we have a user input prompt to save the file by the name of our choice ? any idea how can we do that ? – Jinni Sep 11 '18 at 11:53
  • it asked me "write the name of the file: " and when i key in "Jinni" , it throwing error " name 'Jinni' is not defined " – Jinni Sep 11 '18 at 12:42
  • I didn't notice that you are using python 2.6. sobstitute `input()` with `raw_input()`. see the updated answer. And pay attention, in your updated question you're not closing the file – Gsk Sep 11 '18 at 13:11
  • you always want to close the file at the end. or you use `with open('file_name.txt', 'w+') as fp` which handles the closing by himself, or if you use `fp = open('file_name.txt', 'w+')`, at the end you must call `fp.close()` – Gsk Sep 11 '18 at 15:24