Python脚本将相同的命令应用于文件夹中的每个文件
理想情况下,我希望创建一个Python脚本,将相同的RegEx命令应用于特定文件夹中的所有单个文件-此脚本将命令应用于输入文件,然后将文件保存到同一文件夹,只是使用不同的扩展名(即,Python脚本将相同的命令应用于文件夹中的每个文件,python,regex,Python,Regex,理想情况下,我希望创建一个Python脚本,将相同的RegEx命令应用于特定文件夹中的所有单个文件-此脚本将命令应用于输入文件,然后将文件保存到同一文件夹,只是使用不同的扩展名(即,.txt而不是.tt) 假设我有一个包含5个不同文件的文件夹: FOLDER1 File1.tt File2.tt File3.tt File4.tt File5.tt 我想使用以下命令将.tt文件转换为.txt文件 awk '{print $1"_"$2}' < Fi
.txt
而不是.tt
)
假设我有一个包含5个不同文件的文件夹:
FOLDER1
File1.tt
File2.tt
File3.tt
File4.tt
File5.tt
我想使用以下命令将.tt文件转换为.txt文件
awk '{print $1"_"$2}' < File1.tt | tr -s "\n" " " > File1.txt
awk'{print$1““$2}'File1.txt
但是,我不想将此命令单独应用于每个文件。相反,我想创建一个Python脚本,允许我将此命令应用于文件夹中的每个文件。使用
endswith
和shutil
和os.walk
怎么样-
此脚本将查找扩展名为.tt
的所有文件(通过endswith
)在文件夹C:\Users\fldr
中,如果相应的.txt
文件不存在,则它将创建相应的.txt
文件,并将.tt
的内容复制到该文件夹中的.txt
文件中,即C:\Users\fldr
import os,shutil
folder = r"C:\Users\fldr"
for root, dir, files in os.walk(folder):
for single_file in files:
if single_file.endswith('.tt'):
base, extension = os.path.splitext(single_file)
old_file_path = os.path.join(root,single_file)
new_file_path = os.path.join(folder,base+'.txt')
while not os.path.exists(new_file_path):
shutil.copy(old_file_path, new_file_path)
这是一个简单的、没有痛苦的方法,有很多代码,但是可读性和可维护性。只需将此脚本放在您要操作的目录之外
import os
myfiles_directory = "testing"
def files_in_dir(dirname):
"""
Given a valid directory it will do the listing of files inside that directory
@param: dirname --> Directory where your files are residing.
"""
if(os.path.isdir(dirname)):
return os.listdir(dirname)
def full_filepath(filename, directory):
"""
Given a filename and a directory, construct the full file path,
tracking our current working directory.
@param: filename --> File we want to make full path of.
@param: directory --> The directory to make path against the file.
"""
if(isinstance(filename, list)):
for files in filename:
yield os.path.join(os.path.join(os.getcwd(), directory), files)
def write_rename_file(fullfilepath, current_prefix="tt"):
"""
For simplicity we shall open the file and write it with a new name
based on the other name.
@param: fullfilepath --> The whole file path we want to operate on.
@param: current_prefix --> The prefix we want to get rid of, replacing with txt.
"""
if(fullfilepath.endswith(".txt")):
pass
else:
open_current_file = open(fullfilepath, "r")
open_new = fullfilepath[:-len(current_prefix):] + "txt"
# Preventing creating new file again
if(os.path.exists(open_new)):
pass
else:
open_new_file = open(open_new, "w")
open_new_file.write(open_current_file.read())
open_new_file.close()
os.remove(fullfilepath)
fileslist = files_in_dir(myfiles_directory)
for f in full_filepath(fileslist, myfiles_directory):
print write_rename_file(f)
我希望这对你有用,慢慢来,理解剧本的作用
尝试修改它并满足您的需要。
记住,文件最终被删除了为什么要使用python?为什么不是一个简单的bash脚本<代码>用于f in*;执行awk“{print$1”“$2}”<“$f”| tr-s”\n”“>“${f/.tt/.txt}”;完成先试着写,如果失败了再寻求帮助怎么样?这不是一个代码编写服务。“我想创建一个Python脚本…”什么阻止了你?脚本有更新吗?