我需要打开一个小但数量可变的文件,每个文件都有相同的行数。然后我需要返回每一行的一个元组。我的代码返回一个元组,但每个元素都保留其'\n';如何在它被塞进元组之前去掉它
这是目前为止的代码
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()
我有一个由3个文件组成的测试集,每个文件有5行,每个行表示文件号和行号。代码打印这些测试文件的准确记录
('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')
到目前为止还不错,但是如何在将“\n”放入元组之前从每一行中剥离它呢
我知道有答案!期待您的建议。谢谢&;祝你今天愉快
我认为最简单的方法是修改对
read_fds
的赋值,以便从izip
生成修改的元组:但是,我没有测试过这个
你也可以使用切片的字符串
怎么样:
这将删除字符串右侧的任何换行符
相关问题 更多 >
编程相关推荐