python学习之二

简介: 文件的操作:    打开文件的方式: >>> open('test.txt', 'w')>>> file('test.

文件的操作:

    打开文件的方式: 

>>> open('test.txt', 'w')
<open file 'test.txt', mode 'w' at 0x2b00cac7e6f0>
>>> file('test.txt', 'w')
<open file 'test.txt', mode 'w' at 0x2b00cac7e780>
>>> f = open ('test.txt', 'w')
>>> print f
<open file 'test.txt', mode 'w' at 0x2b00cac7e6f0>
      注: w -> 写操作  r->读操作  a-> 文本末尾添加  r+ ->可读可写 b->二进制读写  需要和w r 配合使用 比如:rb wb

   读文件操作 :

 1. 默认读完

>>> f = open('test1.txt', 'r')
>>> f.read()
 2. 逐行读取文件

>>> f = open('test1.txt', 'r')
>>> f.readline()

>>> f=open('test1.txt', 'r')
>>> f.readline()
'This is the first line in the file.\n'
>>> f.readline()
'this is the second line in the file.\n'
>>> f.readline()
'this is the third line in the file.\n'
>>> f.readline()
'this is the 4th line in the file.\n'
>>> f.readline()
'this is the 5th line in the file.\n'
>>> f.readline()
'this is the 6th line in the file.\n'
>>> f.readline()
'this is the 7th line in the file.\n'
>>> f.readline()
'this is the 8th line in the file.\n'
>>> f.readline()
'this is the 9th line in the file.\n'
>>> f.readline()
'this is the 10th line in the file.\n'
>>> f.readline()
'\n'
>>> f.readline()
''
 3. 读全文,系统自动以‘\n’结尾表示换行,并且每行作为list成员,以逗号分隔!

>>> f = open('test1.txt', 'r')
>>> f.readlines()
>>> f=open('test1.txt', 'r')
>>> f.readlines()
['This is the first line in the file.\n', 'this is the second line in the file.\n', 'this is the third line in the file.\n', 'this is the 4th line in the file.\n', 'this is the 5th line in the file.\n', 'this is the 6th line in the file.\n', 'this is the 7th line in the file.\n', 'this is the 8th line in the file.\n', 'this is the 9th line in the file.\n', 'this is the 10th line in the file.\n', '\n']

for 循环读取文件:

>>> f=open('test1.txt', 'r')
>>> for line in f:
...    print line
... 
This is the first line in the file.

this is the second line in the file.

this is the third line in the file.

this is the 4th line in the file.

this is the 5th line in the file.

this is the 6th line in the file.

this is the 7th line in the file.

this is the 8th line in the file.

this is the 9th line in the file.

this is the 10th line in the file.

以读写方式打开文件,查找偏移量对应的值并读出。

>>> f=open('test2.txt', 'r+')
>>> f.write('0123456789\n')
>>> f.seek(5)
>>> f.read(1)
'5'
>>> f.seek(-3, 2)
>>> f.read(1)
'8'







    

目录
相关文章
|
5月前
|
数据采集 机器学习/深度学习 人工智能
Python基础第一篇(Python概念介绍)
Python基础第一篇(Python概念介绍)
|
6月前
|
Unix Linux 开发者
第一章:介绍和Python基础
第一章:介绍和Python基础
58 1
|
6月前
|
存储 编译器 Python
|
Python
【Python零基础学习入门篇⑤】——第五节:Python中的函数
1️⃣学习目标——明方向 ✅ ✅ ✅ 清楚并掌握函数的基础定义及语法 了解函数的传入参数、函数的返回值、函数的嵌套调用 能够熟练使用一些常用函数的定义及调用 2️⃣ 学习任务——冲鸭!☑️ ☑️ ☑️ ⭐01初识函数 ⭐什么是函数? 函数是组织好的,可重复使用的,用来实现特定功能的代码段。 比如,len()就是Python中的一个内置函数: 它是提前写好的 它可以被重复使用 它是用来实现统计长度这一特定功能的代码段
122 0
【Python零基础学习入门篇⑤】——第五节:Python中的函数
|
IDE 测试技术 Linux
编写Python代码 | 手把手教你入门Python之十
本节重点介绍编写Python代码
2348 0
编写Python代码 | 手把手教你入门Python之十
|
数据采集 网络协议 Linux
Python的使用场景 | 手把手教你入门Python之八
本节介绍了Python应用场景有哪些。