我正在运行一个脚本,用于替换文件名中的德语变音符号。我需要为超过 1700 个文件执行此操作,但在脚本运行一段时间后我收到一条错误消息,指出打开的文件太多。任何人有任何想法如何解决这个问题?非常感谢反馈!
代码:
# -*- coding: utf-8 -*-
''' Script replaces all umlauts in filenames within a root directory and its subdirectories with the English
equivalent (ie. ä replaced with ae, Ä replaced with Ae).'''
import os
import itertools
import logging
from itertools import groupby
##workspace = u'G:\\Dvkoord\\GIS\\TEMP\\Tle\\Scripts\\Umlaut'
workspace = u'G:\\Gis\\DATEN'
log = 'Umlauts.log'
logPath = r"G:\Dvkoord\GIS\TEMP\Tle\Scripts\Umlaut\Umlauts.log"
logMessageFormat = '%(asctime)s - %(levelname)s - %(message)s'
def GetFilepaths(directory):
"""Function returns a list of file paths in a directory tree using os.walk. Parameter: directory
"""
file_paths = []
for root, directories, files in os.walk(directory):
for filename in files:
filepath = os.path.join(root, filename)
file_paths.append(filepath)
## file_paths = list(set(file_paths))
return file_paths
def uniq(input):
output = []
for x in input:
if x not in output:
output.append(x)
return output
def Logging(logFile, logLevel, destination, textFormat, comment):
"""Function writes a log file. Parameters: logFile (name the log file w/extension),
logLevel (DEBUG, INFO, etc.), destination (path under which the log file will be
saved including name and extension), textFormat (how the log text will be formatted)
and comment.
"""
# logging
logger = logging.getLogger(__name__)
# set log level
logger.setLevel(logLevel)
# create a file handler for the log -- unless a separate path is specified, it will output to the directory where this script is stored
logging.FileHandler(logFile)
handler = logging.FileHandler(destination)
handler.setLevel(logLevel)
# create a logging format
formatter = logging.Formatter(textFormat)
handler.setFormatter(formatter)
# add the handlers to the logger
logger.addHandler(handler)
logger.info(comment)
def main():
# dictionary of umlaut unicode representations (keys) and their replacements (values)
umlautDictionary = {
u'Ä': 'Ae',
u'Ö': 'Oe',
u'Ü': 'Ue',
u'ä': 'ae',
u'ö': 'oe',
u'ü': 'ue',
u'ß': 'ss'
}
dataTypes = [".CPG",
".dbf",
".prj",
".sbn",
".sbx",
".shp",
".shx",
".shp.xml",
".lyr"]
# get file paths in root directory and subfolders
filePathsList = GetFilepaths(workspace)
# put all filepaths with an umlaut in filePathsUmlaut list
filePathsUmlaut = []
for fileName in filePathsList:
## print fileName
for umlaut in umlautDictionary:
if umlaut in os.path.basename(fileName):
for dataType in dataTypes:
if dataType in fileName:
## print fileName
filePathsUmlaut.append(fileName)
# remove duplicate paths from filePathsUmlaut
uniquesUmlauts = uniq(filePathsUmlaut)
# create a dictionary for umlaut translation
umap = {
ord(key):unicode(val)
for key, val in umlautDictionary.items()
}
# use translate and umap dictionary to replace umlauts in file name and put them in the newFilePaths list
# without changing any of the umlauts in folder names or upper directories
newFilePaths = []
for fileName in uniquesUmlauts:
pardir = os.path.dirname(fileName)
baseName = os.path.basename(fileName)
newBaseFileName = baseName.translate(umap)
newPath = os.path.join(pardir, newBaseFileName)
newFilePaths.append(newPath)
newFilePaths = uniq(newFilePaths)
# create a dictionary with the old umlaut path as key and new non-umlaut path as value
dictionaryOldNew = dict(itertools.izip(uniquesUmlauts, newFilePaths))
# rename old file (key) as new file (value)
for files in uniquesUmlauts:
for key, value in dictionaryOldNew.iteritems():
if key == files:
comment = '%s'%files + ' wurde als ' '%s'%value + ' umbenannt.'
print comment
if os.path.exists(value):
os.remove(value)
os.rename(files, value)
Logging(log, logging.INFO, logPath, logMessageFormat, comment)
if __name__ == '__main__':
main()
最佳答案
我认为问题出在您的Logging 函数上。每次登录时,您都会创建一个新的 FileHandler 并将其添加到处理程序集中,并且您会为每个重命名的文件执行此操作,因此您很快就会达到打开文件描述符的限制。一次配置您的记录器,然后多次使用它,不要每次使用它时都配置它。
请注意,Logging 中可能不会引发异常;在 Windows 上删除文件需要打开文件进行删除,因此您可以使用记录器最大限度地打开文件,然后在尝试删除文件时失败。
关于Windows 上的 Python 2.7——打开的文件太多,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36474264/
我有一个Ruby程序,它使用rubyzip压缩XML文件的目录树。gem。我的问题是文件开始变得很重,我想提高压缩级别,因为压缩时间不是问题。我在rubyzipdocumentation中找不到一种为创建的ZIP文件指定压缩级别的方法。有人知道如何更改此设置吗?是否有另一个允许指定压缩级别的Ruby库? 最佳答案 这是我通过查看rubyzip内部创建的代码。level=Zlib::BEST_COMPRESSIONZip::ZipOutputStream.open(zip_file)do|zip|Dir.glob("**/*")d
我试图在一个项目中使用rake,如果我把所有东西都放到Rakefile中,它会很大并且很难读取/找到东西,所以我试着将每个命名空间放在lib/rake中它自己的文件中,我添加了这个到我的rake文件的顶部:Dir['#{File.dirname(__FILE__)}/lib/rake/*.rake'].map{|f|requiref}它加载文件没问题,但没有任务。我现在只有一个.rake文件作为测试,名为“servers.rake”,它看起来像这样:namespace:serverdotask:testdoputs"test"endend所以当我运行rakeserver:testid时
我的目标是转换表单输入,例如“100兆字节”或“1GB”,并将其转换为我可以存储在数据库中的文件大小(以千字节为单位)。目前,我有这个:defquota_convert@regex=/([0-9]+)(.*)s/@sizes=%w{kilobytemegabytegigabyte}m=self.quota.match(@regex)if@sizes.include?m[2]eval("self.quota=#{m[1]}.#{m[2]}")endend这有效,但前提是输入是倍数(“gigabytes”,而不是“gigabyte”)并且由于使用了eval看起来疯狂不安全。所以,功能正常,
我需要在客户计算机上运行Ruby应用程序。通常需要几天才能完成(复制大备份文件)。问题是如果启用sleep,它会中断应用程序。否则,计算机将持续运行数周,直到我下次访问为止。有什么方法可以防止执行期间休眠并让Windows在执行后休眠吗?欢迎任何疯狂的想法;-) 最佳答案 Here建议使用SetThreadExecutionStateWinAPI函数,使应用程序能够通知系统它正在使用中,从而防止系统在应用程序运行时进入休眠状态或关闭显示。像这样的东西:require'Win32API'ES_AWAYMODE_REQUIRED=0x0
关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。
Rails2.3可以选择随时使用RouteSet#add_configuration_file添加更多路由。是否可以在Rails3项目中做同样的事情? 最佳答案 在config/application.rb中:config.paths.config.routes在Rails3.2(也可能是Rails3.1)中,使用:config.paths["config/routes"] 关于ruby-on-rails-Rails3中的多个路由文件,我们在StackOverflow上找到一个类似的问题
对于具有离线功能的智能手机应用程序,我正在为Xml文件创建单向文本同步。我希望我的服务器将增量/差异(例如GNU差异补丁)发送到目标设备。这是计划:Time=0Server:hasversion_1ofXmlfile(~800kiB)Client:hasversion_1ofXmlfile(~800kiB)Time=1Server:hasversion_1andversion_2ofXmlfile(each~800kiB)computesdeltaoftheseversions(=patch)(~10kiB)sendspatchtoClient(~10kiBtransferred)Cl
我正在寻找执行以下操作的正确语法(在Perl、Shell或Ruby中):#variabletoaccessthedatalinesappendedasafileEND_OF_SCRIPT_MARKERrawdatastartshereanditcontinues. 最佳答案 Perl用__DATA__做这个:#!/usr/bin/perlusestrict;usewarnings;while(){print;}__DATA__Texttoprintgoeshere 关于ruby-如何将脚
使用带有Rails插件的vim,您可以创建一个迁移文件,然后一次性打开该文件吗?textmate也可以这样吗? 最佳答案 你可以使用rails.vim然后做类似的事情::Rgeneratemigratonadd_foo_to_bar插件将打开迁移生成的文件,这正是您想要的。我不能代表textmate。 关于ruby-使用VimRails,您可以创建一个新的迁移文件并一次性打开它吗?,我们在StackOverflow上找到一个类似的问题: https://sta
好的,所以我的目标是轻松地将一些数据保存到磁盘以备后用。您如何简单地写入然后读取一个对象?所以如果我有一个简单的类classCattr_accessor:a,:bdefinitialize(a,b)@a,@b=a,bendend所以如果我从中非常快地制作一个objobj=C.new("foo","bar")#justgaveitsomerandomvalues然后我可以把它变成一个kindaidstring=obj.to_s#whichreturns""我终于可以将此字符串打印到文件或其他内容中。我的问题是,我该如何再次将这个id变回一个对象?我知道我可以自己挑选信息并制作一个接受该信