位置:学校首页 > 学校动态>南京哪有Python培训班
南京哪有Python培训班,千锋教育隶属于北京千锋互联科技有限公司,每年有数百万名学员受益于千锋组织的技术研讨会,技术培训课,网络公开课及0元教学视频.拥有全国一体化就业保障服务,成为学员信赖的IT职业教育品牌.
用Python将注释行和空行去掉
比如要将/etc/httpd/conf/httpd.conf的注释行和空行去掉并且打印,用一行命令就可以做到:
egrep -v ‘^#|^$’ /etc/httpd/conf/httpd.conf。但这里练习用Python实现
#!/usr/bin/env python
#coding: utf8
import os
def dellines():
#os模块调用linux命令,\cp是为了避免alias里面的cp -i,强制复制文件,不询问是否覆盖
os.system('\cp -r -f /etc/httpd/conf/httpd.conf .')
f = file('httpd.conf')
linenum = 0
while True:
data = f.readline()
if data == '':
break
else:
#个字符为#或者是换行符,就pass,否则就打印这一行
if (data[0] == '#') or (data[0] == '\n'):
pass
else:
linenum += 1
print linenum, data ,
f.close()
if __name__ == '__main__':
dellines()
Python去掉文件中空行
# coding = utf-8
def clearBlankLine():
file1 = open('text1.txt', 'r', encoding='utf-8') # 要去掉空行的文件
file2 = open('text2.txt', 'w', encoding='utf-8') # 生成没有空行的文件
try:
for line in file1.readlines():
if line == '\n':
line = line.strip("\n")
file2.write(line)
finally:
file1.close()
file2.close()
if __name__ == '__main__':
clearBlankLine()