为了账号安全,请及时绑定邮箱和手机立即绑定

如何在 with 语句中将文件名作为变量处理

如何在 with 语句中将文件名作为变量处理

PIPIONE 2023-04-18 14:48:11
我正在尝试将数据写入文件。以下是我如何进行。values = [45, 67, 39]with open(os.path.join(path_class, r'first_file.csv'), 'a') as f: writer = csv.writer(f)        writer.writerow(values)但我想在 first_file.csv 位置有一个变量。我的问题在这里with open(os.path.join(path_class, r'file_name.csv')所以我想要类似的东西:list_of_file = ['first_file.csv', 'second_file.csv']for i in range(0, len(list_of_file):    with open(os.path.join(path_class, r+list_of_file[i]), 'a') as f:        writer = csv.writer(f)        writer.writerow(values)我该怎么做谢谢您花时间回答我的问题。
查看完整描述

2 回答

?
拉丁的传说

TA贡献1789条经验 获得超8个赞

list_of_files = ['first_file.csv', 'second_file.csv']

for file in list_of_files:

    with open(os.path.join(path_class, file), 'a') as f:

        writer = csv.writer(f)

        writer.writerow(values)


查看完整回答
反对 回复 2023-04-18
?
青春有我

TA贡献1784条经验 获得超8个赞

您不一定需要r此处的字符串标志,因为该字符串仅代表 csv 文件名。检查以使用 r 字符串标志。


因此这段代码应该有效:


for i in range(len(list_of_file)):

    with open(os.path.join(path_class, list_of_file[i]), 'a') as f:

        writer = csv.writer(f)

        writer.writerow(values)


查看完整回答
反对 回复 2023-04-18
  • 2 回答
  • 0 关注
  • 101 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信