[英]Python - Execute command line function on every file in a directory?
I have a directory of CSV files that I want to import into MySQL. 我有一个要导入MySQL的CSV文件目录。 There are about 100 files, and doing a manual import is painful. 大约有100个文件,手动导入很麻烦。
My command line is this: 我的命令行是这样的:
mysqlimport -u root -ppassword --local --fields-terminated-by="|" data PUBACC_FR.dat
The files are all of type XX.dat
, ie AC.dat
, CP.dat
, etc. I actually rename them first before processing them (via rename 's/^/PUBACC_/' *.dat
). 这些文件都是XX.dat
类型,即AC.dat
, CP.dat
等。在处理它们之前,我实际上首先对其进行了rename 's/^/PUBACC_/' *.dat
(通过rename 's/^/PUBACC_/' *.dat
)。 Ideally I'd like to be able to accomplish both tasks in one script: Rename the files, then run the command. 理想情况下,我希望能够在一个脚本中完成两项任务:重命名文件,然后运行命令。
From what I've found reading, something like this: 根据我发现的阅读内容,类似这样的内容:
for filename in os.listdir("."):
if filename.endswith("dat"):
os.rename(filename, filename[7:])
Can anyone help me get started with a script that will accomplish this, please? 有人可以帮助我开始使用可以完成此任务的脚本吗? Read the file names, rename them, then for each one run the mysqlimport
command? 读取文件名,重命名它们,然后为每一个运行mysqlimport
命令?
Thanks! 谢谢!
I suppose something like the python code below could be used: 我想可以使用以下类似的python代码:
import subprocess
import os
if __name__ == "__main__":
for f in os.listdir("."):
if (f.endswith(".dat")):
subprocess.call("echo %s" % f, shell=True)
Obviously, you should change the command from echo to your command instead. 显然,您应该将命令从echo改为命令。
See http://docs.python.org/2/library/subprocess.html for more details of using subprocess, or see the possible duplicate. 有关使用子流程的更多详细信息,请参见http://docs.python.org/2/library/subprocess.html ,或查看可能的重复项。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.