pythoniftxt
Ⅰ python讀取txt文件
「'gbk' codec can't decode 。。。。。」是python 的編碼問題。最好你把那個txt的文件先轉換為utf8的格式,再進行讀取,而且讀取文件的那個py文件,文件的第一行加上 # -*- coding:utf-8 -*-
Ⅱ python怎麼匹配txt文件中的某一行的第一個數據,如果匹配,則將這行數據按格式列印出來
importre
yourfile="a.txt"
yourtarget="xxx"
withopen(yourfile,"r")asfi:
forlineinfi:
ifline.strip():
tmp=re.split("s+",line.strip())
iftmp[0]==yourtarget:
print("|"+"|".join(tmp)+"|")
Ⅲ python判斷txt文件首行空行
新建一個用於測試的含多個空行且首行空行的文本文件
然後textfile=open("test.txt","r",encoding="utf-8")
lines=textfile.readlines()
print(lines)
你就會發現問題了
Ⅳ python if判斷的問題,文本111.txt中每行分別為aaa bbb ccc ddd 代碼如下:
#!/usr/bin/python
file=open('/root/weibo/111.txt','r')
fileline=file.readlines()
printfileline#看下fileline是否有東西
forlineinfileline:
ifline=='ccc':
printline
file.close()
Ⅳ python是如何判斷一個txt文件是否為空
獲取文件大小,如果文件大小等於0就是空的,如下:
importos
size=os.path.getsize('d:/abc.txt')
ifsize==0:
print('文件是空的')
else:
print('文件不是空的')
Ⅵ python獲取txt內容並判斷
#!/usr/bin/python
# -*- coding:utf-8 -*-
spath="./123.txt"
def existError(spath):
file=open(spath)
flag=0
for line in file:
#忽略大小寫
if 'error' in str.lower(line):
flag=1
break
return flag
if __name__=="__main__":
flag=existError(spath)
print(str(flag))
Ⅶ 我要用python在txt中查找指定的內容,並且得知該內容在第幾行,該如何做
簡單寫寫,前提是python運行的當前目錄下,有一個xx.txt的文檔。注意else的空格, 不要弄錯了。
s=raw_input('Youfind>>>')
f=open('xx.txt','rb').readlines()
foriinrange(len(f)):
ifsinf[i]:
print'line:',i+1
break
else:
print'sorry!'
Ⅷ python讀取txt文件,查找到指定內容,並做出修改
def modifyip(tfile,sstr,rstr):
try:
lines=open(tfile,'r').readlines()
flen=len(lines)-1
for i in range(flen):
if sstr in lines[i]:
lines[i]=lines[i].replace(sstr,rstr)
open(tfile,'w').writelines(lines)
except Exception,e:
print e
modifyip('a.txt','a','A')
Ⅸ python 里放入txt文件
f=open(r"data.txt")
n=0
for line in f:
n+=1
if n==3:
print(line.split()[0])
break
f.close()
Ⅹ python將txt文件中的字元和數字單獨提取
1、打開pycharm編輯器。