创建单独的输出文件

时间:2018-06-05 19:43:48

标签: python python-3.x

以下示例代码显示我再次运行这些命令。我猜这是做错的方法。

for filename in os.listdir(path):
    with open(os.path.join(path,filename), "r") as infile:
        for line in infile:
            if re.search(r"\b1000\b", line, flags=re.IGNORECASE):
                count1 += 1
                fh.write("{}, ".format(count1))

for filename in os.listdir(path):
    with open(os.path.join(path,filename), "r") as infile:
        for line in infile:
            if re.search(r"\b10G\b", line, flags=re.IGNORECASE):
                count2 += 1
                fh.write("{}, ".format(count2))

2 个答案:

答案 0 :(得分:1)

我希望我能正确理解你的想法。我建议你可以做以下事情。

fh = open("my.csv", "w+")
path = 'my path'

for filename in os.listdir(path):
   with open(os.path.join(path,filename), "r") as infile:
       count1 = 0
       count2 = 0

       for line in infile:
           if re.search(r"\b10G\b", line, flags=re.IGNORECASE):
               count1 += 1

           if re.search(r"\b10G\b", line, flags=re.IGNORECASE):
               count2 += 1

       # write the count value to the csv after reading the file
       fh.write("Count1: {} Count2: {}\n".format(count1, count2))

# close the file reader - otherwise there won't be any content in the csv
fh.close()

答案 1 :(得分:0)

你可以这样做:

fh = open("output.csv", "w")
for filename in os.listdir(path):
with open(os.path.join(path,filename), "r") as infile:
    for line in infile:
        if re.search(r"\b10G\b", line, flags=re.IGNORECASE):
            count1 += 1
            fh.write("{}, ".format(count1))