数据交互

通过控制台进行数据交互

输入数据

input()函数,返回str

向控制台输出

print()函数

print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)

print函数特殊处理

39a072bf-825b-4372-9644-34cc1b609e3c

通过文件进行数据交互

在外存中保存数据的方式包括文件和数据库等

文件和数据库的区别

image

面向文件的输入输出

文件系统:相关知识可以问豆包

文件数据的存储方式:文本方式&&二进制方式

文件的读写方式

打开文件

>>> f.read()
'This is a test file. \nThe code 
is quite simple and 
straightforward, but it builds the 
full list in memory.\n'
>>> f.read()
''
>>> f.seek(0)
0
>>> [line for line in f]
['This is a test file. \n', 'The 
code is quite simple and 
straightforward, but it builds the 
full list in memory.\n']
>>> f.close(0)

  1. 打开文件:open()
    image

  2. 核心读写方法

image

  1. 文件对象的可迭代特性
[line for line in f]

  • 文件对象本身是可迭代对象,可以直接用for循环或列表推导式逐行遍历,非常适合处理大文件(避免一次性加载全部内容到内存)。
  • 遍历后文件指针会自动移动到末尾。
  1. 关闭文件:close()
    f.close()
  • 作用:释放文件资源,断开与文件的连接,避免资源泄漏。

最佳实践:推荐使用with语句自动管理文件关闭,无需手动调用close():

with open("textfile.txt") as f:
    content = f.read()
# 代码块结束后文件自动关闭

5.代码示例逐行解析

>>> f = open("textfile.txt")   # 打开文件
>>> f.read()                  # 读取全部内容,指针移到末尾
'This is a test file.\nThe code is quite simple and straightforward, but it builds the full list in memory.\n'
>>> f.read()                  # 指针已在末尾,返回空字符串
''
>>> f.seek(0)                 # 指针移回开头
0
>>> [line for line in f]      # 逐行遍历,得到行列表
['This is a test file.\n', 'The code is quite simple and straightforward, but it builds the full list in memory.\n']
>>> f.close()                 # 关闭文件

image

Python os 模块文件 / 目录操作详解

image

>>> import os
>>> files = os.listdir()  # 获取当前目录下所有条目

os.listdir():返回的是名称列表,不区分文件和目录,需要结合os.path.isfile()/os.path.isdir()进一步判断类型。


>>> for f in files:
...     print(f)
...
speedTest.py
textfile.txt


os.mkdir():仅能创建单层目录,若要创建多级目录需用os.makedirs()。
>>> os.mkdir("testDIR")   # 创建目录 testDIR
>>> os.mkdir("testDIR2")  # 创建目录 testDIR2
>>> files = os.listdir()  # 再次获取目录条目
>>> for f in files:
...     print(f)
...
testDIR2
testDIR
speedTest.py
textfile.txt

第一次os.listdir():返回初始目录下的两个文件。
执行os.mkdir()后:新增两个目录。
第二次os.listdir():返回包含两个文件和两个目录的完整列表。
posted @ 2026-03-21 17:31  RReally  阅读(2)  评论(0)    收藏  举报
//一下两个链接最好自己保存下来,再上传到自己的博客园的“文件”选项中