Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/360.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何将文件名作为with语句中的变量处理_Python_Csv - Fatal编程技术网

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

Python 如何将文件名作为with语句中的变量处理,python,csv,Python,Csv,我正在尝试将数据写入文件中。以下是我如何进行的 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位置有一个变量 我的问题是open(os.path.join(path\u class,r'file\u name.csv'

我正在尝试将数据写入文件中。以下是我如何进行的

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位置有一个变量
我的问题是open(os.path.join(path\u class,r'file\u 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)
我怎样才能做到这一点
感谢您抽出时间回答我的问题。

列出所有文件=['first\u file.csv'、'second\u file.csv']
对于\u文件列表中的文件:
将open(os.path.join(path_类,文件),“a”)作为f:
writer=csv.writer(f)
writer.writerow(值)
文件列表=['first\u file.csv','second\u file.csv']
对于\u文件列表中的文件:
将open(os.path.join(path_类,文件),“a”)作为f:
writer=csv.writer(f)
writer.writerow(值)

此处不一定需要
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)

此处不一定需要
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)