使用Python 3在CSV文件中查找和替换子文件夹/ TXT

时间:2017-08-17 14:38:45

标签: python python-3.x replace find subdirectory

我列出了csv中的所有查找和替换条目。我的要求是在所有文本文件的子文件夹中执行查找和替换。

这是csv文件的外观:

csvfind_replacement.csv
xxx   ;yyy
111   ;AAA
222   ;BBB
333   ;CCC

操作:

  1. 逐个打开子文件夹中的文本文件
  2. 找到xxx并替换yyy
  3. import os
    import csv
    # CSV file with find and replace format
    with open(r'C:\Users\user\Desktop\csvfind_replacement.csv','rb') as csvfind_replacement.csv:
        reader = csv.reader(csvfind_replacement, delimiter=';')
    
    # walk through all file 
    
    for root, dirs, files in os.walk(r'C:\Users\user\Desktop\test'):
      for name in files:
          file = open(“name”,”w”) 
              for row in reader:
                  replace(row[], column[])
         file.close
    

    以上是我的不完整/非工作代码。只是想知道是否有任何输入可以从CSV中为所有子文件夹完成查找和替换任务。

1 个答案:

答案 0 :(得分:0)

您的代码存在许多问题。 csv.reader是一个迭代器,所以一旦你迭代它,它就是空的。在下面的代码中,我在循环的每次传递中重新创建了阅读器,但最好是制作一个列表:

listReader = list(reader)

一次,在循环之外,然后你可以在循环的每次传递中迭代列表。我会留给你做的。

我将您的CSV文件更改为:

cat csvfind_replacement.csv 
xxx;yyy
111;AAA
222;BBB
333;CCC

否则,分号前面的空格是搜索文本的一部分,我认为你不想要它。

这是我的代码:

import os
import csv

fn = 'csvfind_replacement.csv'
os.chdir(r'/Users/saul/Desktop')

for root, dirs, files in os.walk('csvTest'):
    for name in files:
       print(name)
       if not (name.endswith('txt') ):
           continue
       text = open(os.path.join(root, name)).read()
       print("Before:")
       print(text)
       csvfile = open(fn, newline='')
       reader = csv.reader(csvfile, delimiter = ';')  
       for row in reader:
            if row:
                text=text.replace(row[0], row[1])
       print('\nAfter')
       print(text)
       file = open(name,'w')
       file.write(text)
       file.close
       csvfile.close()      

我的csvTest文件夹有两个文本文件text1.txt和test2.txt,还有一个MacOS创建的名为.DS_Store的文件。它有一个子文件夹子,有一个名为test3.txt的文本文件。

以下是我的测试结果:

.DS_Store
test1.txt
Before:
line 1 xxx
line 2 111
line 3 222
line 4 333


After
line 1 yyy
line 2 AAA
line 3 BBB
line 4 CCC

test2.txt
Before:
line 1 111
line 2 222222
line 3 abcd
line 4 xxx
line 5 333111xxx


After
line 1 AAA
line 2 BBBBBB
line 3 abcd
line 4 yyy
line 5 CCCAAAyyy

test3.txt
Before:
line 1 xxxxxxx
line 2 111111
line 3 222111
line 4 3333


After
line 1 yyyyyyx
line 2 AAAAAA
line 3 BBBAAA
line 4 CCC3
相关问题