如何通过文件列表循环itertools?

时间:2018-04-27 03:52:07

标签: python loops itertools

我设法为单个文件创建此文件以切割文件中的行。我想只拿奇数。

filename = sys.argv[1]
filename2 = sys.argv[2]

with open(filename) as f:
    items = itertools.islice(f, 0, None, 2)

    x = (list(items))
    final = "".join(x)

with open(filename2, 'a+') as bb:
    bb.write(final)

以上代码工作正常。但我需要手动指定文件名。如果我有100个文件需要切片怎么办?

上面的代码输出示例。它将切割/删除偶数行。

Input file
a
b
c
d
e

Output file
a
c
e

我在想循环。到目前为止,这是我的解决方案。

# Directory where it contains my pat files.
mydir = "C:\\Users\\Desktop\\Scripts\\"
files = filter(lambda x: x.endswith('.pat'), os.listdir(mydir))

# print(list(files))
# ['filepat1.pat', 'filepat2.pat', 'filepat3.pat'.......]

i = 0
new_file = 'file{}.pat'.format(i)

for file in files:
    with open(file) as f:
       items = itertools.islice(f, 0, None, 2)
       x = (list(items))
       final = "".join(x)
       #print(final)
       for item in items:
           i +=1
           new_file = 'file{}.pat'.format(i)
           with open(new_file, 'a+') as ww:
               ww.write(final)

我的错误是什么?好像它错过了循环。

1 个答案:

答案 0 :(得分:2)

如果我错了,请纠正我,但来自for item in items:的代码看起来很奇怪。根据我的理解,你试图从一个文件中拉出奇数行并将它们存储在一个新文件中,对吗?

你可以像这样重写:

mydir = "C:\\Users\\Desktop\\Scripts\\"
files = filter(lambda x: x.endswith('.pat'), os.listdir(mydir))

#print(list(files))

for i, file in enumerate(files):
    with open(file) as f:
       items = itertools.islice(f, 0, None, 2)
       x = (list(items))
       final = "".join(x)
       #print(final)

       new_file = 'file{}.pat'.format(i)
       with open(new_file, 'a+') as ww:
           ww.write(final)