将数据写入文件的正确方式是什么?

2024-10-01 02:26:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图将一些数据写入文件,但我使用的路径有一些问题

这是我的代码:

my_path = r'c:\data\XYM\Desktop\MyFolder 7-sep'

with open(my_path + '\\' + 'Vehicles_MM' + '\\' + name_vehicile + '-AB.txt', 'w') as output:
    writer = csv.writer(output, delimiter = '\t')
    writer.writerow(headers)
    writer.writerow(data)
    for vehicle_loc_list in vehicle_loc_dict.values():
        for record_group in group_records(vehicle_loc_list):
            writer.writerow(output_record(record_group))

这是我收到的错误:

FileNotFoundError: [Errno 2] No such file or directory: 'c:\\data\\XYM\\Desktop\\MyFolder 7-sep\\Vehicles_MM\\20200907-AB.txt'

Tags: pathoutputdatamygrouprecordlocsep
2条回答

您应该使用其中一个内置项来处理路径。要么{}要么{}

# with os.path:
import os.path as p
filename = p.join(my_path, "Vehicles_MM", name_vehicle + "-AB.txt")
assert p.exists(p.dirname(filename))

# with pathlib.Path:
from pathlib import Path
my_path = Path("c:\data\XYM\Desktop\MyFolder 7-sep")
filename = my_path.joinpath("Vehicles_MM", name_vehicle + "-AB.txt")
assert filename.parent.exists()

根据评论中披露的情况,问题是您正试图写入一个子目录c:\data\XYM\Desktop\MyFolder 7-sep\Vehicle_MM\,该子目录不存在,实际上您不想写入

修复方法是删除目录分隔符\\;可能使用不同的分隔符。比如说,

with open(my_path + '\\' + 'Vehicles_MM-' + name_vehicile + '-AB.txt', 'w') as output:

如果确实要写入此子目录,则必须确保它存在,然后才能尝试打开其中的文件

os.makedirs(my_path + '\\' + 'Vehicles_MM', exist_ok=True)
with open(...

使用pathlib.Path时,同样的东西更具可读性

from pathlib import Path

my_path = Path(r'c:\data\XYM\Desktop\MyFolder 7-sep')
vehicles_mm = my_path / 'Vehicles_MM'
vehicles_mm.mkdir(parents=True, exist_ok=True)
filename = vehicles_m / name_vehicile + '-AB.txt'
with filename.open('w') as output:
   ...

相关问题 更多 >