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
總結
以上是生活随笔為你收集整理的python数据获取手段包括哪些_python开发应用-本地数据获取方法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 服务承诺一句话经典89句
- 下一篇: python怎么查询元素是否在列表中_p