从不同目录中的输入创建新的 CSV 文件
Creating new CSV files from inputs in different directory
我只是想用 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
你的问题出在这一行:
reports_dir = os.chdir(os.path.join(cur_dir, args.dir))
os.chdir()
没有 return 任何东西,它只是执行请求的操作 - 更改当前工作目录。来自与 REPL 的互动会话:
>>> import os
>>> result = os.chdir("/Users/mattdmo/")
>>> result
>>>
为了您的目的,您只需要
reports_dir = os.path.join(cur_dir, args.dir)
一切就绪。
我只是想用 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
你的问题出在这一行:
reports_dir = os.chdir(os.path.join(cur_dir, args.dir))
os.chdir()
没有 return 任何东西,它只是执行请求的操作 - 更改当前工作目录。来自与 REPL 的互动会话:
>>> import os
>>> result = os.chdir("/Users/mattdmo/")
>>> result
>>>
为了您的目的,您只需要
reports_dir = os.path.join(cur_dir, args.dir)
一切就绪。