python本地数据获取_python开发应用-本地数据获取方法

文件的打开、读写和关闭

文件的打开:

file_obj=open(filename,mode='r',buffering=-1,...)

filename是强制参数

mode是可选参数,默认值是r

buffering是可选参数,默认值为-1(0代表不缓冲,1或大于1的值表示缓冲一行或指定缓冲区大小)

f1=open('e:/test/data.txt')

f1=open('e:\\test\data.txt')

f2=open(r'e:/test/data.txt','w')

文件相关函数

返回值:

1、open()函数返回一个文件(file)对象

2、文件对象可迭代

3、有关闭和读写文件的相关的函数/方法

写文件:

file_obj.write(str):讲一个字符串写入文件

with open('e:\\test\\firstpro.txt','w') as f:

f.write('Hello,World!')

file_obj.read(size):从文件中至多读出size字节数据,返回一个字符串

file_obj.read():读文件直到文件结束,返回一个字符串

with open('e:/test/firstpro.txt') as f:

p1=f.read(5)

p2=f.read()

p1

'Hello'

p2

',World!'

其它读写函数:

file_obj.readlines():读取多行数据

file_obj.readline():读取一行数据

file_obj.writelines():写入多行数据

with open('e:/test/data.txt') as f:

f.readlines()

文件读写例子:将文件data.txt中的字符串前面加上1、2、3、4、...后写入到另一个文件data1.txt中。

data.txt

apple

banana

car

pear

with open('e:/test/data.txt') as f1:

cNames=f1.readlines()

for i in range(0,len(cNames)):

cNames[i]=str(i+1)+' '+cNames[i]

with open('e:/test/data1.txt','w') as f2:

f2.writelines(cNames)

其它文件相关函数:

file_obj.seek(offset,whence=0):在文件中移动文件指针,从whence(0表示文件头部,1表示当前位置,2

表示文件尾部)偏移offset个字节,whence参数可选,默认值为0。

with open('e:/test/data.txt','a+') as f:

f.writelines('\n')

f.writelines(s)

f.seek(0)

cNames=f.readlines()

print(cNames)

['apple\n', 'banana\n', 'car\n', 'pear\n', 'Tencent Technology Company Limited']

标准文件:

stdin:标准输入

stdout:标准输出

stderr:标准错误

newName=input('Enter the name of new company:')

Enter the name of new company:Alibaba

print(newName)

Alibaba

实际上是sys模块提供的函数实现的

import sys

sys.stdout.write('hello')

hello5

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值