Python的文件读取一般有三种
- read()
- readline()
- readlines()
三个方法都可以接收一个变量用来限制每次读取的数据量
1. read()
- 优点: 读取整个内容,可以放在一个字符串变量当中使用
- 确定: 如果内容文件非常大,那就非常占用内存
with open('test.txt') as textFile:
contents = textFile.read()
print(contents)
>>>
<class 'str'>
3.14159 26535 89793 23846
26433 83279 50288 41971
69399 37510 58209 74944
59230 78164 06286 20899
86280 34825 34211 70679
82148 08651 32823 06647
09384 46095 50582 23172
# 一个简单的文件复制demo
# 1. open
# 打开源文件
file_read = open('test.txt')
# 打开目标文件
file_write = open('test1.txt','w')
# 2. read write
text = file_read.read()
file_write.write(text)
# 3. close
file_read.close()
file_write.close()
2. readline() 避免一次性读取太多内容 对内存造成压力 一般会使用readline()
readline()方法每次读取一行;返回的是一个字符串对象readline()方法可以一次性读取一行内容- 方法执行后,会把 文件指针 移动到下一行,准备再次读取
with open('test.txt') as testFile:
contents = testFile.readline()
print(contents)
>>>
3.14159 26535 89793 23846 <class 'str'>
# 使用一个while循环 逐行的读取内容
file = open('test.txt')
while True:
a = file.readline()
# 判断是否读取到内容
if not a:
break
print(a)
file.close()
# 一个简单的大文件复制demo
# 1. open
# 打开源文件
file_read = open('test.txt')
# 打开目标文件
file_write = open('test1.txt','w')
# 2. read write
# 复制大文件 就需要使用readline()
while True:
# 读取一行内容
text = file_read.readline()
# 判断是否读取到内容
if not text:
break
file_write.write(text)
# 3. close
file_read.close()
file_write.close()
3. readlines()
- 一次性读取整个文件;自动将文件内容分析成一个行的 ==> 列表对象
with open('test.txt') as testFile:
contents = testFile.readlines()
print(contents)
>>>
<class 'list'> ['3.14159 26535 89793 23846 \n', '26433 83279 50288 41971 \n', '69399 37510 58209 74944 \n', '59230 78164 06286 20899 \n', '86280 34825 34211 70679 \n', '82148 08651 32823 06647 \n', '09384 46095 50582 23172 \n', '53594 08128 48111 74502 \n', '84102 70193 85211 05559 \n', '64462 29489 54930 38196 \n', '44288 10975 66593 34461 \n', '28475 64823 37867 83165 \n', '27120 19091 45648 56692 \n', '34603 48610 45432 66482']
文件/目录的常用管理操作
-
在 终端 / 文件浏览器 ,中 可以执行常规的 文件 / 目录 管理操作,例如:
- 创建,重命名,删除,改变路径,查看目录内容,........
-
在
python中,如果希望通过程序实现上述功能,需要导入OS模块
文件操作
| 序号 | 方法名 | 说明 | 示例 |
|---|---|---|---|
| 01 | rename | 重命名文件 | os.rename(源文件名,目标文件名) |
| 02 | remove | 删除文件 | os.remove(文件名) |
目录操作
| 序号 | 方法名 | 说明 | 实例 |
|---|---|---|---|
| 01 | listdir | 目录列表 | os.listdir(目录名) |
| 02 | mkdir | 创建目录 | os.mkdir(目录名) |
| 03 | rmdir | 删除目录 | os.rmdir(目录名) |
| 04 | getcwd | 获取当前目录 | os.getcwd() |
| 05 | chdir | 修改工作目录 | os.chdir(目标目录) |
| 06 | path.isdir | 判断是否是文件 | os.path.isdir(文件路径) |
提示: 文件或目录操作都支持 相对路径 和 绝对路径