我想遍历文件夹中的csv文件列表,对每个文件执行一些计算(总是相同的),并为每个文件保存一个新文件。
文件具有这样的数据结构:
"[Couplet 10 : Jul]
C'est 1.3.5 sur la plaque
Fais ton biz coupe ta plaque
C'est JU, JU , JUL qui débarque
Pour mes blancs , beurres et blacks
Passe moi un stunt pour voir si sa cabre
Embrouilles sur le sable , cocotiers sur la sappe
Je dors pas je suis tout pâle, je dis pas que je suis 2Pac
Je dis pas lui je vais le tuer si j'ai même pas 2 balles
C'est pour ceux qui XXX fais gaffe les shmits l'impact
Son anti B.D.H anti tapette",1
(...)到目前为止,我已经:
match = "^[\(\[].*?[\)\]]"
for d in directories:
dir = os.path.join(data_dir, d)
files_ = [os.path.join(dir, f)
for f in os.listdir(dir)
if f.endswith(".csv")]
for f in files_:
with open(f, 'rb') as f1, open('out.csv', 'wb') as out_file:
reader = csv.reader(f1, delimiter='\t')
for item in list(reader):
item = re.sub(match, ' ', item, flags=re.MULTILINE)
out_file.write(item)但我得到了这个回溯:
File "process_csv.py", line 75, in load_data
item = re.sub(match, ' ', item, flags=re.MULTILINE)
File "/Users/username/anaconda/lib/python2.7/re.py", line 155, in sub
return _compile(pattern, flags).sub(repl, string, count)
TypeError: expected string or buffer实现这一目标的最佳途径是什么?
发布于 2017-09-28 17:27:39
根据再文档,re.sub期望第三个参数为字符串。但是list(reader)返回带有CSV字段的列表,而不是字符串。因此,您需要从这个列表中提取字符串并将其传递给re.sub。
item = re.sub(match, ' ', item[0], flags=re.MULTILINE)或者任何你需要在计算中使用的索引。
为了更好地理解它,请尝试:
test.csv:
a
b
c
>>> f = open('test.csv')
>>> reader = csv.reader(f)
>>> list(reader)
[['a'], ['b'], ['c']]更新
要使它处理实际数据示例,请执行以下操作:
" (默认情况下)或更改regex。''。在python2中,open不接受newline参数,而是使用io包。io文件打开通常具有相同的签名。来自CSV包文件的解释:如果未指定newline='‘,则嵌入在引号字段中的换行符将无法正确解释,并且在写上使用\r\n行尾的平台上将添加额外的\r。指定newline='‘应该是安全的,因为csv模块执行自己的(通用)换行符处理。
with open(f, 'rb', newline='') as f1, open('out.csv', 'wb', newline='') as out_file:
...sub最后,修正代码:
import io
...
match = "^[\(\[].*?[\)\]]"
for d in directories:
dir = os.path.join(data_dir, d)
files_ = [os.path.join(dir, f)
for f in os.listdir(dir)
if f.endswith(".csv")]
for f in files_:
with io.open(f, 'rb', newline='') as f1, io.open('out.csv', 'wb') as out_file:
reader = csv.reader(f1)
writer = csv.writer(out_file)
for item in reader:
writer.writerow([
re.sub(match, ' ', item[0], flags=re.MULTILINE),
item[1]
])https://stackoverflow.com/questions/46474780
复制相似问题