【问题标题】:Can't save files to different dir in python无法将文件保存到python中的不同目录
【发布时间】:2020-01-24 19:29:05
【问题描述】:

所以我正在尝试将大量 txt 文件转换为 csv 并将它们保存在不同的文件夹中。 我可以隐藏它们没问题,但它们总是保存在读取它们的同一个文件夹中。 我试过加入路径,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("\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

【问题讨论】:

  • 在写入文件之前尝试os.chdir
  • 三个点 Path('.../ 不是有效路径。
  • @thebjorn,这也是我最初的想法,但我认为他们只是用用户名之类的东西来混淆他们的本地文件系统。我有点担心这条线'CSV Combined'/file 在字符串上执行除法运算符?假设这只是一个复制错误。
  • @OsmosisJonesLoL 不,这只是一个 pathlib 操作。
  • 我明白了,仍然对他为什么要在他的路径前面合并 CSV 并附加文件中的其余内容感到困惑。我会假设 open(saveTo/fileName, 'w+') 是我们想要的。

标签: python python-3.x csv path


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2020-07-31
    • 1970-01-01
    • 1970-01-01
    • 2021-12-21
    • 1970-01-01
    • 1970-01-01
    • 2012-05-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多