如何删除文件中的空白行

时间:2019-11-25 14:15:06

标签: python

首先我有一个txt文件,我想做两件事:

  1. 删除所有以开头的内容,除了第一行,然后输出文件

  2. 删除文件的所有空白行

对于步骤1:

with open ("txt","r") as file1:
    temp=file1.read()
    c=re.sub(r"#\w+.*|#\s.*","",txt)
    print(c,file=open("temp","a"))

对于步骤2:

with open("temp","r+") as file2:
    txt=file2.read()
    c=re.sub(r"\n",' ',txt)
    print(c,file=open("txt","a"))

这是我的txt:

#*&^%$
sunday
monday
#comment
rainy
#weather
#1998
cloudy

该步骤正确但该步骤不正确,我该如何修改?如果我只想删除第2行〜第6行,我该怎么做?

2 个答案:

答案 0 :(得分:0)

我认为这就是您想要做的

def uncomment(filepath):
  with open(filepath, "r+", encoding="utf-8") as f:
    lines = f.readlines()[1:] # read all the lines except the first
    lines = [line.split("#")[0].rstrip() for line in lines]
    filtered_lines = [line for line in lines if line != '']
    return filtered_lines

答案 1 :(得分:0)

使第一行保持不变

代码

with open ("txt.txt","r") as ifile, open('result.txt', 'w') as ofile:
  for i, line in enumerate(ifile):
    if i == 0:
      ofile.write(line)  # keeps first line
    else:
      new_line = line.rstrip().split('#')[0] # ignore blank line and remove comments
      if new_line: 
        ofile.write(new_line + '\n')

测试

输入文件: txt.txt

#*&^%$
sunday  # good day
monday

#comment
rainy # tomorrow
#weather



#1998
cloudy

输出文件(保留第一行): results.txt

#*&^%$
sunday  
monday
rainy 
cloudy