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

问题描述

我正在尝试将一些数据写入文件,但是我使用的路径存在一些问题。

这是我的代码

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'

解决方法

根据评论的启示,问题在于您试图写入一个不存在的子目录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:
   ...
,

您应该使用内置函数之一来处理路径。 os.pathpathlib.Path

# 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()