我如何在每次运行代码时创建一个带有时间和日期的全新CSV文件?

huangapple go评论87阅读模式
英文:

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

问题

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,

<details>
<summary>英文:</summary>

I&#39;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(&quot;Summary&quot;, &#39;w&#39;)
writer2 = csv.writer(data2)
writer2.writerow([&quot;Trial#&quot;, &quot;Button 0 Clicks&quot;, &quot;Button 1 Clicks&quot;, &quot;Button 2 Clicks&quot;, &quot;Outside Clicked&quot;, &quot;Time&quot;])
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&#39;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() &lt; 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() &gt; button_radius:
clickoutsidebutton += 1
x = pygame.mouse.get_pos()[0]
if x &lt;= 425:
timenow = time.time()
writer = csv.writer(data)
writer.writerow([trialnum, 201, time.asctime(time.localtime(time.time()))])
elif x &lt;= 850:
timenow = time.time()
writer = csv.writer(data)
writer.writerow([trialnum, 200, time.asctime(time.localtime(time.time()))])
elif x &gt; 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&quot;Button {i}&quot;, 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&#39;s currently giving me the error that no such file or directory exists, however, I&#39;m trying to have it create a new file so it shouldn&#39;t be searching for the file to exist already. 
</details>
# 答案1
**得分**: 1
假设您每次运行脚本或模块时都想创建一个新文件。
使用 `datetime` 模块获取当前日期和时间,并使用一些格式化函数,如 `strftime()`,将时间表示为字符串。使用它来生成新的文件名。
以下是一个精确到一秒的示例。如果您期望您的脚本并发运行或快于一秒内运行,您可以考虑添加更多精度或类似 `uuid` 的内容,以避免名称冲突。
```python
from datetime import datetime
import csv
... # 任何初始化代码
file_name = f"my_file_{datetime.now().strftime('%Y%m%d_%H%M%S')}.csv"
with open(file_name, "w") as csvfile:
... # 写入您的 CSV 内容

这将每次生成新的文件名,例如:

/my_file_20230615_161352.csv

这种命名约定的额外属性是,当结果文件按字母顺序排序时,它们也会按时间顺序排序。

英文:

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&quot;my_file_{datetime.now().strftime(&#39;%Y%m%d_%H%M%S&#39;)}.csv&quot;
with open (file_name, &quot;w&quot;) 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.

答案2

得分: 0

from datetime import datetime
import csv

current_time = datetime.now()

fields = ["年", "月", "日", "时", "分", "秒"]
rows = [[current_time.year, current_time.month, current_time.day, 
         current_time.hour, current_time.minute, current_time.second]]

file_name = "日期时间.csv"
with open (file_name, "w") as csvfile:
    csvwriter = csv.writer(csvfile) 
    csvwriter.writerow(fields) 
    csvwriter.writerows(rows)
英文:
from datetime import datetime
import csv
current_time = datetime.now()
fields = [&quot;Year&quot;, &quot;Month&quot;, &quot;Day&quot;, &quot;Hour&quot;, &quot;Minute&quot;, &quot;Second&quot;]
rows = [[current_time.year, current_time.month, current_time.day, 
current_time.hour, current_time.minute, current_time.second]]
file_name = &quot;DateTime.csv&quot;
with open (file_name, &quot;w&quot;) as csvfile:
csvwriter = csv.writer(csvfile) 
csvwriter.writerow(fields) 
csvwriter.writerows(rows)

huangapple
  • 本文由 发表于 2023年6月16日 05:05:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/76485502.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定