宝捱科技网
您的当前位置:首页python读取txt文件时怎么去掉空格

python读取txt文件时怎么去掉空格

来源:宝捱科技网


Python读取TXT文件可以通过replace()函数来去除TXT文件中的空格,基本结构:replace(to_replace, value) 前面是需要替换的值,后面是替换后的值。

代码如下:

import os
import sys
#os.chdir('E:\') # 跳到D盘
#if not os.path.exists('1.txt'): # 看一下这个文件是否存在
# exit(-1) #,不存在就退出
lines = open('M:\casia\test1.txt').readlines() #打开文件,读入每一行
print lines
fp = open('M:\casia\test2.txt','w') #打开你要写得文件pp2.txt
for s in lines:
 fp.write(s.replace(' ','')) # replace是替换,write是写入
fp.close() # 关闭文件
print 'ok'

更多Python相关技术文章,请访问Python教程栏目进行学习!

显示全文