[英]Python 2.7 Output from text files without last blank line
I've started to learn Python and I stucked on one task - I have 10 text files and I am trying to write from them two outputs: Output 1 should look like folder and name of file header folder and name of file header ... 我已经开始学习Python,并且坚持执行一项任务-我有10个文本文件,并且尝试从中写入两个输出:输出1应该看起来像文件夹和文件头文件夹名称以及文件头名称...
Output 2 should look like folder and name of file | 输出2应该看起来像文件夹和文件名| text |
文字| text |
文字| text folder and name of file |
文本文件夹和文件名| text |
文字| text |
文字| text ...
文字...
Although I looked throught many of questions, I have not found, how to delete (or not write) last blank row - there should be always only text. 尽管我看了很多问题,但我还没有发现如何删除(或不写)最后一个空白行-应该始终只有文本。 All solutions I tried (tell(), rstrip(), ...) deleted all signs for new line, so I had file like folder and name of file headerfolder and name of file header.
我尝试过的所有解决方案(tell(),rstrip(),...)删除了所有换行符,所以我有了诸如folder之类的文件,并且文件头文件夹的名称和文件头的名称。 Ufortunatelly because of the task definition I am allowed to use only glob and re, so helpful sys is forbidden for me :(
不幸的是,由于任务定义,我只能使用glob和re,因此对我来说有用的sys被禁止:(
I would really appreciate your help with that, this task is for me really challenging but now I do not know how to continue :) 非常感谢您的帮助,这项任务对我来说确实是一项挑战,但现在我不知道如何继续:)
Thanks for any advice and have a nice day ;) 感谢您的任何建议,祝您有美好的一天;)
Code I am using: 我正在使用的代码:
import re, glob
file_list = glob.glob('./input/*txt')
for file_name in file_list:
input_file = open(file_name, 'r')
output_1 = open('file_1', 'a')
output_2 = open('file_2', 'a')
for line in input_file:
if re.search(r'\s{2,}\S{4,}\s{1}\S+:.*', line):
output_2.write(file_name.replace('.txt','|') + line)
if re.search(r'\s{3,}\S{3,16}\s+X?\s[A-Z]{3,4}\d?\s+\d{1,3}.*', line):
field = re.findall('\S{3,16}\s{3,}', line) + re.findall('\s{2}\d{1,3}.*', line)
field_join = '|'.join(field)
field_clear = re.sub(r'(\s){2,}', '', field_join)
field_list = re.sub(' ', '|', field_clear, 1)
output_1.write(file_name.replace('.txt','|') + field_list + '\n')
output_2.close()
output_1.close()
input_file.close()
At the beginning of the loop just continue
(immediately go to next loop iteration without executing any more code) if it's a blank line: 如果循环为空行,则在循环开始时
continue
(立即执行下一个循环迭代,而不执行任何其他代码):
for line in input_file:
if not line.strip():
continue
# etc
EDIT: For only the last line if it's blank: 编辑:仅对于最后一行,如果为空:
input_file = input_file.readlines()
last_iter = len(input_file) - 1
for idx, line in enumerate(input_file):
if idx == last_iter and not line.strip():
break
Or before the loop: 或循环之前:
input_file = input_file.readlines()
if not input_file[-1].strip():
input_file = input_file[:-1]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.