【发布时间】:2019-04-30 13:05:11
【问题描述】:
我正在编写一个程序。但我有一个问题。
我想从文件中删除第一个 x 字符。
msg = clientsocket.recv(1024)
if len(msg) < 2:
print "Exit"
break
try:
myfile = open('logs/demo.txt','a')
msg = msg.replace('\n','')
msg = msg.replace(' ','')
myfile.write(msg)
myfile.flush()
myfile.close()
except IOError:
print "write error"
finally:
myfile.close()
try:
myfile.close()
myfile=open("logs/demo.txt","r+")
firstdata=myfile.read()
firstdata.replace('\n','')
firstdata.replace(' ','')
son = firstdata.rfind("#")
firstdata = firstdata[:son]
print firstdata
#os.remove("logs/demo.txt")
myfile.close()
os.remove("logs/demo.txt")
myfile = open('logs/demo.txt','a')
firstdata = firstdata.replace('\n','')
firstdata = firstdata.replace(' ','')
myfile.write(firstdata[son:])
myfile.flush()
myfile.close()
except IOError:
print "read error"
finally:
myfile.close()
这段代码太长,我打开文件3次。
我想要:
删除前:
In file : "asdfghjkl#mnbvc#qwerty#poiuyt"
删除后:
In file : "poiuyt"
【问题讨论】:
标签: python python-2.7 file