Can';t在python中将文件保存到不同的目录
因此,我试图将大量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 不管我怎么做,我都无法将其保存到我想要的文件夹中。这太搞笑了。我读过的链接在底部Can';t在python中将文件保存到不同的目录,python,python-3.x,csv,path,Python,Python 3.x,Csv,Path,因此,我试图将大量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已转换\ac
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)
这对我很有效-使用
路径
属性和方法来构造新文件的路径。它获取工作区中的所有文本文件
,并在保存到
路径中创建新文件(扩展名为'.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())
在写入文件之前尝试
os.chdir
三点路径(“…/
不是一个有效的路径。@thebjorn,这也是我最初的想法,但我认为他们只是用用户名之类的东西混淆了本地文件系统。我有点担心这行'CSV Combined'/file
对字符串执行除法运算符?假设这只是一个复制错误。@OsmosisJonesLoL不,这是错误的st是一个pathlib操作。我明白了,他仍然不明白为什么要在路径前面合并CSV,然后附加文件中的其余内容。我假设open(saveTo/fileName,'w+)
就是他想要的。