How to remove spaces when reading txt files in python

Release: 2019-07-08 09:02:08
Original
11874 people have browsed it

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'
Copy after login

更多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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!