无法在python中将文件保存到其他目录

2024-06-16 10:13:18 发布

您现在位置: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

不管我怎么做,我都无法将其保存到我想要的文件夹中。这太搞笑了。我读过的链接在底部

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/

Creating files and directories via Python


Tags: 文件csvtoinhttps文件夹withline
1条回答
网友
1楼 · 发布于 2024-06-16 10:13:18

这对我很有用-使用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())

相关问题 更多 >