因此,我试图将大量txt文件转换为csv文件,并将其保存在不同的文件夹中。 我可以隐藏它们没有问题,但它们总是保存在读取它们的同一文件夹中。 我尝试了joinpath,os.path.join,folder+filename,open(文件'w+'和'x'和'w')。 covertToCSV函数中的print语句始终为我提供正确的文件夹,然后显示该文件未在该文件夹中生成
…\nlps\11-CSV转换\CSV组合
…\nlps\11-CSV转换\CSV组合
…\nlps\11-CSV已转换\acmission\u 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
Writing to a new directory in Python without changing directory
How to write file in a different directory in python?
https://thispointer.com/how-to-create-a-directory-in-python/
这对我很有用-使用
Path
属性和方法来构造新文件的路径。它获取workspace
中的所有文本文件,并在saveto
路径中生成新文件(具有'.csv'
扩展名)相关问题 更多 >
编程相关推荐