所以我正在尝试将大量txt文件转换为csv并将它们保存在不同的文件夹中。 我可以毫无问题地掩盖它们,但它们总是保存在读取它们的同一文件夹中。 我尝试过joinpath,os.path.join,folder+filename,open(文件'w+'和'x'和'w'(。 covertToCSV 函数中的打印语句总是给我正确的文件夹,然后显示文件不是在该文件夹中制作的。
...lps\11-CSV 已转换\CSV 组合
...lps\11-CSV 已转换\CSV 组合
...lps\11-CSV 已转换\Admission_Consult.csv
无论我尝试什么,我都无法将其保存到我想要的文件夹中。这越来越搞笑了。我通读过的链接在底部。
import sys
import csv
from pathlib import Path
workspace = Path('.../nlps/11-CSV converted')
saveTo = Path('.../nlps/11-CSV converted/CSV Combined')
def openFiles(dir):
filePaths = list(workspace.glob('*.txt'))
return filePaths
# Converts given file to CSV with one column with tabs as delimiter
def convertToCSV(filePaths):
for fileName in filePaths:
with open(fileName, 'r') as in_file:
stripped = (line.strip() for line in in_file)
lines = (line.split("t") for line in stripped if line)
fileName = fileName.with_suffix('.csv')
newFile = workspace.joinpath('CSV Combined')
file = newFile.joinpath(fileName)
print(saveTo)
print(newFile)
print(file)
with open('CSV Combined'/file, 'w+') as out_file:
writer = csv.writer(out_file)
writer.writerows(lines)
https://docs.python.org/3/library/pathlib.html
https://docs.python.org/3/library/os.html#os.chmod
https://docs.python.org/3/library/functions.html#open
https://docs.python.org/3.8/library/csv.html
在不更改目录的情况下写入 Python 中的新目录
如何在python中将文件写入不同的目录?
https://thispointer.com/how-to-create-a-directory-in-python/
通过 Python 创建文件和目录
这对我有用 - 使用Path
属性和方法来构造新文件的路径。 它获取workspace
中的所有文本文件,并在saveto
路径中创建新文件(扩展名为'.csv'
(。
import os
from pathlib import Path
workspace = Path(os.getcwd(),'output')
saveto = Path(workspace,'CSV Combined')
#saveto.mkdir() # if it does not exist
for p in workspace.glob('*.txt'):
new = Path(saveto,p.name)
new = new.with_suffix('.foo')
#print(f'save:{p} to {new}')
with p.open() as infile, new.open('w') as outfile:
# process infile here
#outfile.write(processed_infile)
outfile.write(infile.read())