pythonpython-3.xcsvfileimport-csv

How do I create a brand new csv file with the time and date in it every time I run my code?


I'm trying to create a new CSV each time I run my code. The title will include some user input and the current date and time.

import pygame
import csv
import time 
from datetime import datetime

# Initialize pygame starts 
pygame.init()

# Set the dimensions of the screen
screen_width = 1275
screen_height = 750


# Set the colors
white = (255, 255, 255)
black = (0, 0, 0)

# Set the font
font = pygame.font.SysFont('Arial', 20)

# Set the button properties
button_radius = 70
button_x_spacing = 400
button_y_spacing = 200

# Set the button positions
button_positions = [
    (button_x_spacing, button_y_spacing),
    (button_x_spacing, button_y_spacing + 200),
    (button_x_spacing, button_y_spacing + 400)
]

# Initialize the screen
screen = pygame.display.set_mode((screen_width, screen_height))

# Set the caption
pygame.display.set_caption("Marmoset Buttons")

# Set the clock
clock = pygame.time.Clock()

# Set the counters
button0click = 0
button1click = 0
button2click = 0
clickoutsidebutton = 0
trialnum = 0

# Psuedorandom sequence of numbers
sequence = [1,1,2,2,1,2,1,0,1,1, 1,2,1,0,1,0,1,2,1,1, 2,1,0,1,2,1,1,0,1,2, 2,1,0,2,1,1,1,0,1,1,
           1,1,0,1,1,1,2,0,2,1, 2,1,0,1,0,1,1,2,2,1, 1,0,1,1,0,0,1,1,2,2, 1,1,2,1,1,2,1,0,1,1,
           1,1,1,0,1,1,2,0,2,1, 0,1,1,2,1,0,1,2,1,0, 1,1,0,1,1,2,1,2,1,0, 2,1,2,1,1,2,1,1,0,1,
           1,0,1,1,0,1,1,1,1,1, 1,1,2,1,1,1,0,1,1,2, 1,2,1,0,1,2,2,2,1,0, 1,2,1,0,0,1,2,1,2,0,
           1,0,1,1,1,0,1,1,2,1, 0,1,2,2,1,1,1,0,1,1, 1,0,1,2,0,1,0,1,1,2, 0,1,2,1,2,1,2,2,1,0,
           1,1,1,0,1,1,0,1,1,0, 1,2,2,1,0,1,1,2,0,1, 1,0,1,2,1,0,1,2,1,0, 1,0,1,1,2,2,1,1,0,0,
           1,2,1,2,1,1,1,0,1,0, 1,1,0,1,2,1,1,2,1,0, 1,2,1,1,0,1,0,1,1,0, 1,2,0,2,1,2,1,0,0,1,
           1,1,1,1,0,0,1,2,0,1, 0,1,2,0,1,2,1,2,1,0, 1,0,1,2,1,1,2,0,1,2, 0,0,1,0,2,1,2,1,2,1,
           1,2,2,2,1,1,2,1,1,0, 1,2,1,1,0,2,1,2,1,1, 1,2,2,1,1,2,1,0,0,1, 2,1,2,1,0,2,1,2,0,0,
           1,0,1,1,2,2,1,0,1,0, 0,1,2,1,1,0,1,2,0,1, 1,0,0,1,2,1,2,1,0,0, 1,2,0,0,2,1,0,2,1,1,
           1,1,1,1,2,1,1,0,1,1, 2,1,0,1,1,0,1,2,1,0, 0,1,2,1,2,1,0,1,2,1, 2,1,0,2,1,2,1,1,2,1,
           1,1,0,1,1,1,2,1,1,1, 2,1,2,1,0,0,1,2,1,2, 1,0,1,2,1,2,0,1,2,2, 2,0,1,2,1,2,1,0,1,1,
           1,2,1,0,1,2,0,2,2,2, 1,2,2,1,1,0,1,1,0,0, 1,1,0,1,0,0,1,2,1,2, 1,0,2,1,2,1,2,1,0,1,
           1,2,1,1,0,1,1,0,0,1, 1,1,1,2,1,1,0,1,1,1, 1,2,1,0,2,2,1,2,0,1, 1,1,2,2,1,0,1,2,1,0,
           1,2,0,1,1,0,1,1,2,1, 1,2,2,2,1,1,1,0,1,0, 1,2,0,0,0,1,2,2,0,1, 0,2,1,0,0,1,2,2,2,1,
           1,1,2,1,0,1,0,1,2,1, 1,2,1,0,1,1,2,1,0,2, 1,0,2,2,1,0,1,0,2,1, 1,0,2,1,2,1,1,0,0,1,
           1,2,1,2,1,1,1,0,1,1, 1,1,0,0,1,2,1,2,1,0, 1,2,1,2,2,1,0,1,0,0, 2,1,0,2,0,1,0,1,2,1,
           1,1,0,1,0,1,1,1,0,1, 1,2,1,0,1,0,1,2,1,0, 2,1,2,2,1,0,1,0,1,1, 2,1,2,0,1,2,1,2,0,0,
           1,1,2,0,2,1,2,1,1,0, 1,2,1,0,0,1,1,2,1,2, 1,2,2,1,1,1,1,2,0,0, 1,2,1,0,0,2,1,0,2,1,
           1,0,1,1,2,1,2,0,1,2, 2,1,0,1,1,0,1,2,1,0, 0,1,0,1,2,1,1,2,1,0, 2,2,1,0,0,1,2,1,2,1]

# Truncating list 
trials = int(input("Number of trials: "))
n = len(sequence)
for i in range(0, n - trials):
    sequence.pop()

AnimalName = input("Animal Name: ")
StepName = input("Step: ")
thedatetime = datetime.now()
date = thedatetime.date()
thetime = thedatetime.strftime("%H:%M:%S")
title = AnimalName + "_S" + StepName + "_" + str(date) + "_" + str(thetime)

# Write headers to csv file
with open(title, 'w') as data:
    writer = csv.writer(data)
    writer.writerow(["Trial#", "Event Code", "Time"])

# For loop parsing through sequence 
for i in sequence:

    trialnum += 1

    if trialnum%10 == 0:
        if trialnum == 10:
            data2 = open("Summary", 'w')
            writer2 = csv.writer(data2)
            writer2.writerow(["Trial#", "Button 0 Clicks", "Button 1 Clicks", "Button 2 Clicks", "Outside Clicked", "Time"])
            writer2.writerow([trialnum, button0click, button1click, button2click, clickoutsidebutton, time.asctime(time.localtime(time.time()))])
        else:
            writer2.writerow([trialnum, button0click, button1click, button2click, clickoutsidebutton, time.asctime(time.localtime(time.time()))])

    # Delay between buttons 
    screen.fill(black)
    pygame.display.update()
    pygame.time.delay(500)

    # While loop variable 
    button_clicked = False

    # Starts Timer 
    start_time = pygame.time.get_ticks()

    timenow = time.time()
    writer = csv.writer(data)
    writer.writerow([trialnum, i, time.asctime(time.localtime(time.time()))])

    # Loops while button isn't clickeed 
    while button_clicked == False:

        # Time out for 15 seconds 
        seconds = (pygame.time.get_ticks() - start_time)/1000
        if seconds == 15:
            timenow = time.time()
            writer = csv.writer(data)
            writer.writerow([trialnum, 4, time.asctime(time.localtime(time.time()))])
            break

        # Checks when screen is touched 
        for event in pygame.event.get():
            if event.type == pygame.MOUSEBUTTONDOWN:

                # Distance between point touched and button 
                distance_button = pygame.math.Vector2(button_positions[i]) - pygame.math.Vector2(pygame.mouse.get_pos())

                # Checks if distance is within button 
                if distance_button.length() < button_radius:

                    button_clicked = True

                    timenow = time.time()
                    writer = csv.writer(data)
                    writer.writerow([trialnum, 150, time.asctime(time.localtime(time.time()))])

                    # Counts which buttons were pressed 
                    if i == 0:
                        button0click += 1
                    elif i == 1:
                        button1click += 1
                    elif i == 2:
                        button2click += 1

                # Counts when click was outside of button 
                elif distance_button.length() > button_radius:
                    clickoutsidebutton += 1
                    x = pygame.mouse.get_pos()[0]
                    if x <= 425:
                        timenow = time.time()
                        writer = csv.writer(data)
                        writer.writerow([trialnum, 201, time.asctime(time.localtime(time.time()))])
                    elif x <= 850:
                        timenow = time.time()
                        writer = csv.writer(data)
                        writer.writerow([trialnum, 200, time.asctime(time.localtime(time.time()))])
                    elif x > 850:
                        timenow = time.time()
                        writer = csv.writer(data)
                        writer.writerow([trialnum, 202, time.asctime(time.localtime(time.time()))])   

        # Draws the button 
        pygame.draw.circle(screen, white, button_positions[i], button_radius)
        text_surface = font.render(f"Button {i}", True, black)
        text_rect = text_surface.get_rect(center=button_positions[i])
        screen.blit(text_surface, text_rect)
        pygame.display.update()

# Printing results 
print("Button 0 was clicked: " + str(button0click) + " times.")
print("Button 1 was clicked: " + str(button1click) + " times.")
print("Button 2 was clicked: " + str(button2click) + " times.")
print("The area around the button was clicked: " + str(clickoutsidebutton) + " times.")
data.close()
data2.close()

It's currently giving me the error that no such file or directory exists, however, I'm trying to have it create a new file so it shouldn't be searching for the file to exist already.


Solution

  • Assuming you want to create a new file each time you run your script or module. Use datetime module to obtain current date and time and use some formatting function, like strftime() to represent time as string. Use it to generate new file name.

    Below is an example with precision up to one second. If you expect your scripts to run concurrently or faster than within period of one second, you might consider adding more precision or something like uuid, to avoid name collision.

    from datetime import datetime
    import csv
    
    ... # any initialization code
    
    file_name = f"my_file_{datetime.now().strftime('%Y%m%d_%H%M%S')}.csv"
    with open (file_name, "w") as csvfile:
       ... # write content of your csv
    

    This will produce new file name each time, e.g.:

    /my_file_20230615_161352.csv
    

    Bonus property of such naming convention is that when result files are sorted alphabetically, they will be also sorted chronologically.