Python 创建单独的输出文件

Python 创建单独的输出文件,python,python-3.x,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

下面是示例代码,显示我正在再次运行这些命令。我猜这样做是不对的

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))
你可以做:

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))

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

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()

这里的问题是什么?这里的问题相同:。你只是把我的答案粘贴成一个新问题(甚至没有接受它!!)。问题是什么?我需要能够将这些计数值打印到单个.CSV文件中,这可能是重复的。打开的每个文件将只占用输出中的一行。希望这有意义。:)谢谢你的耐心。我是python新手。也许最好分享我的整个脚本,向您展示我试图实现的目标。@ChuckSlayton:我看到您在上面的代码中添加了更多的行。如果您的目标是搜索第二个字符串,只需使用第二个正则表达式向代码中添加第二个计数器变量和elif语句。我理解正确了吗?我想完成的是读取目录中每个.txt文件的行,计算值并对它们执行算术函数。每个.txt将填充一行.csv文件。因此,如果我有30个.txt文件,那么在.csv文件中我将有30行。@ChuckSlayton:上述解决方案执行以下操作。对于目录中的每个文件,它逐行读取并在每行中搜索两个不同的正则表达式。处理完整个文件后,两个计数器值将写入输出csv文件中的一行。希望这有帮助!这是工作!但是,以下行似乎不起作用:elif re.search(r“\b1000\b”,line,flags=re.IGNORECASE)和re.search(r“\bnotco*\b”,line,flags=re.IGNORECASE):count4+=1