Python标准库使用:文件读写、日期时间操作问题

原创 灰太狼 2025-03-03 15:54 77阅读 0赞

在Python标准库中,我们主要通过open()函数进行文件的读写。以下是常见的一些问题及解决方法:

  1. 打开文件
    ```python

    打开文件读取

    file = open(‘filename.txt’, ‘r’)
    content = file.read()
    print(content)

打开文件写入

file = open(‘filename.txt’, ‘w’)
file.write(‘Hello, World!’)
file.close()

  1. 2. **关闭文件**:
  2. 使用`close()`方法可以关闭打开的文件。
  3. 3. **读写错误**:
  4. 例如,如果尝试在只读模式下写入,会抛出异常。需要确保你有适当的模式('r' for read, 'w' for write)。
  5. 4. **日期时间操作**:
  6. Python标准库中的`datetime``time`模块提供了一系列的日期时间操作。
  7. ```python
  8. import datetime
  9. # 创建日期时间对象
  10. dt = datetime.datetime.now()
  11. print(dt)
  12. # 日期时间格式化
  13. formatted_date = dt.strftime('%Y-%m-%d %H:%M:%S')
  14. print(formatted_date)
  15. # 处理时间(不包括日期)对象
  16. time_obj = datetime.time(15, 30))
  17. print(time_obj)
  18. # 时间加减操作
  19. new_time = time_obj + datetime.timedelta(minutes=20)
  20. print(new_time)

请根据实际需求选择相应操作。

文章版权声明:注明蒲公英云原创文章,转载或复制请以超链接形式并注明出处。

发表评论

表情:
评论列表 (有 0 条评论,77人围观)

还没有评论,来说两句吧...

相关阅读