【发布时间】:2021-10-12 15:18:46
【问题描述】:
我只是想用 Python 修改一个 CSV 文件。
当所有文件都在同一个目录中时,一切都很好。
现在输入文件与输出文件位于不同的目录中,一切都崩溃了,显然 b/c 文件不存在?
我首先发现了这个: open() in Python does not create a file if it doesn't exist
然后我学会了切换到目录,这帮助我循环了目标目录中的 CSV: Moving up one directory in Python
当我运行命令时:
python KWRG.py ../Weekly\ Reports\ -\ Inbound/Search\ Activity/ 8/9/2021
我会得到:
Traceback (most recent call last): File "KWRG.py", line 15, in <module> with open(args.input, 'r') as in_file, open(args.output, 'w') as out_file: IsADirectoryError: [Errno 21] Is a directory: '../Weekly Reports - Inbound/Search Activity/'
对不起,如果我在这里遗漏了明显的内容,但是为什么没有在我将脚本指向的目录中创建文件(或根本没有)?
代码:
import csv
import argparse
import os
# Create a parser to take arguments
#...snip...
cur_dir = os.getcwd()
reports_dir = os.chdir(os.path.join(cur_dir, args.dir))
for csv_file in os.listdir(reports_dir):
# Shorthand the name of the file
#...snip...
# Open the in and out files
with open(csv_file, 'r') as in_file, open(f'{out_name}-Search-Activity-{args.date}.csv', 'w+') as out_file:
# Re-arrange CSV
# EOF
【问题讨论】:
-
你使用的是什么操作系统?
-
寻求调试帮助的问题(“为什么这段代码不起作用?”)应包括所需的行为、特定问题或错误和所需的最短代码作为格式化文本(不是图像)在问题本身中。没有明确的问题陈述的问题对其他读者没有用处。请参阅:minimal reproducible example。具体来说,请提供您收到的错误/回溯的全文,并提供导致错误的程序输入的具体示例。
-
我使用的是 Mac - Big Sur 11.5。
-
文件名中不能包含
/字符。那是目录分隔符。请改用-或.或其他内容。 -
这个脚本既没有被指向,也没有试图创建名称中带有“/”的文件。
标签: python csv file operating-system