Python3学习笔记——Modules & Files

日期与时间
# 日期与时间     datetime     date(),time(),datetime()
import datetime
mon_8_2025 = datetime.date(year=2025, month=3, day=8)
mon_8_2025 = datetime.date(2025, 3, 8)
print(mon_8_2025) 

time_13_14min_52sec = datetime.time(hour=13, minute=14, second=52)
time_13_14min_52sec = datetime.time(13, 14, 52)
print(time_13_14min_52sec) 

timestamp= datetime.datetime(year=2025, month=3, day=8, hour=13, minute=14, second=52)
timestamp = datetime.datetime(2025, 3, 8, 13, 14, 52)
print (timestamp)
#输出
2025-03-08
13:14:52
2025-03-08 13:14:52
as 关键字
# 将 matplotlib.pyplot 别名为 plt       
# pip install matplotlib安装库
from matplotlib import pyplot as plt # type: ignore
x = [1, 2, 3, 4, 5]
y = [2, 3, 5, 7, 11]
plt.plot(x, y)
plt.show()
# 将日历别名为 c
import calendar as c
print(c.month_name[1])

输出:

导入
# 方法一
import module
module.function()

# 方法二
from module import function
function()

# 方法三    from module import *不建议使用,因为它会导致本地命名空间混乱,并使命名空间不清晰。
from module import *
function()
 random.randint() 和 random.choice()
# randint()方法提供了从整数范围中进行均匀随机选择的功能    
# choice()方法提供了从序列中均匀选择随机元素的功能

# 返回给定范围内的随机整数 N,使得 start <= N <= end
import random
#  random.randint(开始,结束)
r1 = random.randint(0, 10)  
print(r1) # 随机整数,其中 0 <= r1 <= 10 

# 打印序列中的一个随机元素
seq = ["a", "b", "c", "d", "e"]
r2 = random.choice(seq)
print(r2) # 序列中的随机元素

# file1 内容
# def f1_function():
#	  print("这是一个方法")

# file2 与 file1 必须在同一目录下
# import file1
from file1 import f1_function

# 现在我们可以使用 f1_function,因为我们导入了 file1
f1_function()
#输出
January
3
d
这是一个方法
#file.py
def f1_function():
	#   return "Hello World"
    print("这是一个方法")
文件对象&Readline方法
# 文件对象     with as  【文件对象跟变量进行关联】
with open('somefile.text') as file_object:
    print(file_object)    #文件对象的字符串表示  <_io.TextIOWrapper name='somefile.text' mode='r' encoding='cp936'>
# <_io.TextIOWrapper: 这是文件对象的类型。TextIOWrapper 是 Python 中用于文本文件的 I/O 包装器,它处理文本文件的读写。
# name='somefile.text':这表示打开的文件名是 'somefile.text'。
# mode='r':这是打开文件的模式。'r' 表示文件是以只读模式打开的。
# encoding='cp936':这是文件的字符编码。'cp936' 是指在 Windows 上常见的简体中文编码(也称为 GBK)。
with open('somefile.text', 'r', encoding='cp936') as file_object:
    content = file_object.read()
    print(content)   #输出文件的内容

# Readline方法   读取 Python 文件中的一行    如果存在下一行,则后续操作将提取文件中的下一行
with open('somefile.text') as story_object:
  print(story_object.readline())    #仅打印文件内容的第一行
#输出
<_io.TextIOWrapper name='somefile.text' mode='r' encoding='cp936'>
111
222
333

111
将 JSON 文件解析为字典
# 将 JSON 文件解析为字典
# 使用 json.load 和打开的文件对象将内容读入 Python 字典
import json
with open('file.json') as json_file:
  python_dict = json.load(json_file)
print(python_dict.get('userId'))    #输出10
#file.json
{ 
    "userId": 10
}
文件
#  附加到文件
# 使用标志写入打开的文件'w'会覆盖文件中所有先前的内容。为了避免这种情况,我们可以改为追加到文件中。使用'a'标志作为 的第二个参数open()。如果文件不存在,将创建该文件以用于追加模式。
with open('shopping.txt', 'a') as shop:
  shop.write('Tomatoes, cucumbers, celery\n')

# 读取文件全部内容
with open('shopping.txt') as text_file:
  text_data = text_file.read()
print(text_data)

# Readlines 方法     一次读取一行
with open('shopping.txt') as file_object:
  file_data = file_object.readlines()
print(file_data)
for line in file_data:    #遍历列表并打印
  print(line)

# 写入文件
# 使用 打开的文件open()仅供读取。'r'默认情况下会向其传递第二个参数。要写入文件,首先通过'w'参数以写入权限打开文件。然后使用该.write()方法写入文件。如果文件已存在,则所有先前的内容都将被覆盖。
with open('diary.txt','w') as diary:
  diary.write('Special events for today')
#输出
Tomatoes, cucumbers, celery

['Tomatoes, cucumbers, celery\n']
Tomatoes, cucumbers, celery
#shopping.txt
Tomatoes, cucumbers, celery
#diary.txt
Special events for today
csv.DictWriter类
import csv
# 写入数据到 CSV 文件
# 当用 open 函数打开 CSV 文件时,建议使用 newline=''     是为了确保在 Windows 上正确处理换行符
with open('companies.csv', 'w',newline='') as csvfile:           
  fieldnames = ['name', 'type']
  writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
  writer.writeheader()
  writer.writerow({'name': 'Codecademy', 'type': 'Learning'})
  writer.writerow({'name': 'Google', 'type': 'Search'})
"""
运行上述代码后,companies.csv将包含以下信息:
name,type
Codecademy,Learning
Google,Search
"""
# 读取并打印 CSV 文件内容
with open('companies.csv','r') as csvfile:
  reader = csv.reader(csvfile)          #csv.reader:用于读取文件并逐行打印
  for row in reader:
    print(row)

#输出
['name', 'type']
['Codecademy', 'Learning']
['Google', 'Search']
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值