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

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

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

问题

  1. import pygame
  2. import csv
  3. import time
  4. from datetime import datetime
  5. # Initialize pygame starts
  6. pygame.init()
  7. # Set the dimensions of the screen
  8. screen_width = 1275
  9. screen_height = 750
  10. # Set the colors
  11. white = (255, 255, 255)
  12. black = (0, 0, 0)
  13. # Set the font
  14. font = pygame.font.SysFont('Arial', 20)
  15. # Set the button properties
  16. button_radius = 70
  17. button_x_spacing = 400
  18. button_y_spacing = 200
  19. # Set the button positions
  20. button_positions = [
  21. (button_x_spacing, button_y_spacing),
  22. (button_x_spacing, button_y_spacing + 200),
  23. (button_x_spacing, button_y_spacing + 400)
  24. ]
  25. # Initialize the screen
  26. screen = pygame.display.set_mode((screen_width, screen_height))
  27. # Set the caption
  28. pygame.display.set_caption("Marmoset Buttons")
  29. # Set the clock
  30. clock = pygame.time.Clock()
  31. # Set the counters
  32. button0click = 0
  33. button1click = 0
  34. button2click = 0
  35. clickoutsidebutton = 0
  36. trialnum = 0
  37. # Psuedorandom sequence of numbers
  38. 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,
  39. 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,
  40. 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,
  41. 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,
  42. 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,
  43. 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,
  44. 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,
  45. 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,
  46. 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,
  47. 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,
  48. 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,
  49. 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,
  50. 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,
  51. 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,
  52. 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,
  53. 1,
  54. <details>
  55. <summary>英文:</summary>
  56. 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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Name = 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:

  1. trialnum += 1
  2. if trialnum%10 == 0:
  3. if trialnum == 10:
  4. data2 = open(&quot;Summary&quot;, &#39;w&#39;)
  5. writer2 = csv.writer(data2)
  6. 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;])
  7. writer2.writerow([trialnum, button0click, button1click, button2click, clickoutsidebutton, time.asctime(time.localtime(time.time()))])
  8. else:
  9. writer2.writerow([trialnum, button0click, button1click, button2click, clickoutsidebutton, time.asctime(time.localtime(time.time()))])
  10. # Delay between buttons
  11. screen.fill(black)
  12. pygame.display.update()
  13. pygame.time.delay(500)
  14. # While loop variable
  15. button_clicked = False
  16. # Starts Timer
  17. start_time = pygame.time.get_ticks()
  18. timenow = time.time()
  19. writer = csv.writer(data)
  20. writer.writerow([trialnum, i, time.asctime(time.localtime(time.time()))])
  21. # Loops while button isn&#39;t clickeed
  22. while button_clicked == False:
  23. # Time out for 15 seconds
  24. seconds = (pygame.time.get_ticks() - start_time)/1000
  25. if seconds == 15:
  26. timenow = time.time()
  27. writer = csv.writer(data)
  28. writer.writerow([trialnum, 4, time.asctime(time.localtime(time.time()))])
  29. break
  30. # Checks when screen is touched
  31. for event in pygame.event.get():
  32. if event.type == pygame.MOUSEBUTTONDOWN:
  33. # Distance between point touched and button
  34. distance_button = pygame.math.Vector2(button_positions[i]) - pygame.math.Vector2(pygame.mouse.get_pos())
  35. # Checks if distance is within button
  36. if distance_button.length() &lt; button_radius:
  37. button_clicked = True
  38. timenow = time.time()
  39. writer = csv.writer(data)
  40. writer.writerow([trialnum, 150, time.asctime(time.localtime(time.time()))])
  41. # Counts which buttons were pressed
  42. if i == 0:
  43. button0click += 1
  44. elif i == 1:
  45. button1click += 1
  46. elif i == 2:
  47. button2click += 1
  48. # Counts when click was outside of button
  49. elif distance_button.length() &gt; button_radius:
  50. clickoutsidebutton += 1
  51. x = pygame.mouse.get_pos()[0]
  52. if x &lt;= 425:
  53. timenow = time.time()
  54. writer = csv.writer(data)
  55. writer.writerow([trialnum, 201, time.asctime(time.localtime(time.time()))])
  56. elif x &lt;= 850:
  57. timenow = time.time()
  58. writer = csv.writer(data)
  59. writer.writerow([trialnum, 200, time.asctime(time.localtime(time.time()))])
  60. elif x &gt; 850:
  61. timenow = time.time()
  62. writer = csv.writer(data)
  63. writer.writerow([trialnum, 202, time.asctime(time.localtime(time.time()))])
  64. # Draws the button
  65. pygame.draw.circle(screen, white, button_positions[i], button_radius)
  66. text_surface = font.render(f&quot;Button {i}&quot;, True, black)
  67. text_rect = text_surface.get_rect(center=button_positions[i])
  68. screen.blit(text_surface, text_rect)
  69. 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()

  1. 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.
  2. </details>
  3. # 答案1
  4. **得分**: 1
  5. 假设您每次运行脚本或模块时都想创建一个新文件。
  6. 使用 `datetime` 模块获取当前日期和时间,并使用一些格式化函数,如 `strftime()`,将时间表示为字符串。使用它来生成新的文件名。
  7. 以下是一个精确到一秒的示例。如果您期望您的脚本并发运行或快于一秒内运行,您可以考虑添加更多精度或类似 `uuid` 的内容,以避免名称冲突。
  8. ```python
  9. from datetime import datetime
  10. import csv
  11. ... # 任何初始化代码
  12. file_name = f"my_file_{datetime.now().strftime('%Y%m%d_%H%M%S')}.csv"
  13. with open(file_name, "w") as csvfile:
  14. ... # 写入您的 CSV 内容

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

  1. /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.

  1. from datetime import datetime
  2. import csv
  3. ... # any initialization code
  4. file_name = f&quot;my_file_{datetime.now().strftime(&#39;%Y%m%d_%H%M%S&#39;)}.csv&quot;
  5. with open (file_name, &quot;w&quot;) as csvfile:
  6. ... # write content of your csv

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

  1. /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

  1. from datetime import datetime
  2. import csv
  3. current_time = datetime.now()
  4. fields = ["年", "月", "日", "时", "分", "秒"]
  5. rows = [[current_time.year, current_time.month, current_time.day,
  6. current_time.hour, current_time.minute, current_time.second]]
  7. file_name = "日期时间.csv"
  8. with open (file_name, "w") as csvfile:
  9. csvwriter = csv.writer(csvfile)
  10. csvwriter.writerow(fields)
  11. csvwriter.writerows(rows)
英文:
  1. from datetime import datetime
  2. import csv
  3. current_time = datetime.now()
  4. fields = [&quot;Year&quot;, &quot;Month&quot;, &quot;Day&quot;, &quot;Hour&quot;, &quot;Minute&quot;, &quot;Second&quot;]
  5. rows = [[current_time.year, current_time.month, current_time.day,
  6. current_time.hour, current_time.minute, current_time.second]]
  7. file_name = &quot;DateTime.csv&quot;
  8. with open (file_name, &quot;w&quot;) as csvfile:
  9. csvwriter = csv.writer(csvfile)
  10. csvwriter.writerow(fields)
  11. 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:

确定