无法将文件保存到python中的其他目录中
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了无法将文件保存到python中的其他目录中相关的知识,希望对你有一定的参考价值。
因此,我正在尝试将大量的txt文件转换为csv并将其保存在其他文件夹中。我可以秘密地掩盖它们,但是它们始终保存在读取它们的文件夹中。我试过了joinpath,os.path.join,文件夹+文件名,打开(文件“ w +”,“ x”和“ w”)。CovertToCSV函数中的打印语句始终为我提供正确的文件夹,然后显示该文件夹中未包含该文件。
... nlps 11-CSV转换 CSV组合
... nlps 11-CSV转换 CSV组合
... nlps 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(" ") 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
属性和方法构造新文件的路径:
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'):
name = p.name.replace(p.suffix,'.csv')
new = Path(saveto,name)
## print(p,new)
with open(p) as infile, open(new,'w') as outfile:
outfile.write(infile.read())
以上是关于无法将文件保存到python中的其他目录中的主要内容,如果未能解决你的问题,请参考以下文章