简体   繁体   English

从多个同时打开的文件行中删除“ \\ n”

[英]strip '\n' from lines of multiple simultaneously opened files

I need to open a small but variable number of files, each of which has the same number of lines. 我需要打开少量但可变的文件,每个文件具有相同的行数。 I then need to return a tuple of the lines in each. 然后,我需要在每行中返回一个元组。 My code returns a tuple, but each element retains its '\\n'; 我的代码返回一个元组,但是每个元素保留其'\\ n'; how to strip this before it gets packed into the tuple? 如何在打包到元组之前将其剥离?

this is the code so far 这是到目前为止的代码

files = ['file1', 'file2', 'file3']
fds = [ open(file) for file in files ] # gets all file open at same time
read_fds = izip( *fds )
for tpl in read_fds:
    print tpl    # will become a 'yield' stmt once the '\n' is sorted
for fd in fds:
    fd.close()

I have a test set of 3 files, each with 5 lines, each which indicates file number line number. 我有一个包含3个文件的测试集,每个文件有5行,每个文件指示文件号行号。 The code prints this accurate record of these test files. 该代码将打印这些测试文件的准确记录。

('f1ln1\n', 'f2ln1\n', 'f3ln1\tthis\tthat\n')
('f1ln2\n', 'f2ln2\n', 'f3ln2\tthis\tthat\n')
('f1ln3\n', 'f2ln3\n', 'f3ln3\tthis\tthat\n')
('f1ln4\n', 'f2ln4\n', 'f3ln4\tthis\tthat\n')
('f1ln5\n', 'f2ln5\n', 'f3ln5\tthis\tthat\n')

So far so good, but how to strip() that '\\n' from each line before it gets packed into the tuple? 到目前为止一切都很好,但是如何在将每一行中的'\\ n'打包到元组中之前从中剥离(\\ n)?

I know there's an answer out there! 我知道那里有一个答案! Looking fwd to suggestions. 期待提出建议。 Thank you & have a great day. 谢谢,祝你有美好的一天。

You can also use slicing of the string 您还可以使用字符串切片

for tpl in read_fds:
    list_stripped = []
    for s in tpl:
        list_stripped.append(s[:-1])
    print tuple(list_stripped)

How about: 怎么样:

for tpl in read_fds:
    templist = []
    for item in tpl:
        templist.append(item.rstrip("\n"))
    print tuple(templist)

This will remove any newline character on the right side of the string 这将删除字符串右侧的所有换行符

I think the easiest way would be to modify the assignment to read_fds so that it generates modified tuples from izip : 我认为最简单的方法是修改对read_fds的赋值,以便它从izip生成修改后的元组:

read_fds = (tuple(s.rstrip() for s in tup) for tup in izip(*fds))

However, I have not tested this. 但是,我尚未对此进行测试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM