Home  >  Article  >  Backend Development  >  How to remove spaces when reading txt files in python

How to remove spaces when reading txt files in python

尚
Original
2019-06-26 15:41:1911887browse

How to remove spaces when reading txt files in python

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教程栏目进行学习!

The above is the detailed content of How to remove spaces when reading txt files in python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn