Python 在打开刚刚使用 re.search 找到的文件时不返回此类文件或目录
我正在尝试打开许多文件夹中的特定文件,其名称以“.alleles.txt”结尾。我搜索该文件并找到它,但当
它返回: IOError: [Errno 2] No such file or directory: 'abca3.alleles.txt'
我尝试打开它时,
for eachfile in filelisting:
if re.search('\.alleles\.txt$', eachfile):
allelesfile = open(eachfile, 'r')
print '2'
。目录由以下方式指定:
folder = 'E:\\All Data'
folderlisting = os.listdir(folder)
for eachfolder in folderlisting:
print eachfolder
if os.path.isdir(folder + '\\' + eachfolder):
filelisting = os.listdir(folder + '\\' + eachfolder)
I am trying to open a specific file in many folders, with the name ending '.alleles.txt'. I search for the file and it is found, but then it returns:
IOError: [Errno 2] No such file or directory: 'abca3.alleles.txt'
when I try and open it.
for eachfile in filelisting:
if re.search('\.alleles\.txt
Directory is specified by:
folder = 'E:\\All Data'
folderlisting = os.listdir(folder)
for eachfolder in folderlisting:
print eachfolder
if os.path.isdir(folder + '\\' + eachfolder):
filelisting = os.listdir(folder + '\\' + eachfolder)
, eachfile):
allelesfile = open(eachfile, 'r')
print '2'
Directory is specified by:
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您应该使用
glob
。试试这个You should be using
glob
. Try this您如何获取
文件列表
?如果您使用 filelisting = os.walk(directoryname) ,那么它会返回一个特殊的元组。你看过吗?并且,
filelisting
是否包含文件的完整路径?如果文件位于脚本目录以外的目录中,例如存储在directoryname
变量中,则必须以这种方式打开它们:在您输入信息之前,我们无法提供有关您的问题的更多信息这里(实际的
filelisting
值等)。How did you obtain the
filelisting
? If you usedfilelisting = os.walk(directoryname)
then it resturns a special tuple. Did you look at it?And, does
filelisting
contain the full path of the files? If the files are in a directory other than the script directory, say it's stored in thedirectoryname
variable, you have to open them this way:We can't give more information about your question until you put information here (actual
filelisting
value, etc).我怀疑您的某些文件名包含非 ASCII 字符。尝试
记下
u'...'
前缀。如果没有它,os.listdir()
可能会默默地删除或 ASCIIfy 文件名中的非 ASCII 字符,这当然会导致无效的文件名。另请参阅此问题。这在
os.listdir(path)的文档
:
I have a suspicion that some of your filenames contain non-ASCII characters. Try
Note the
u'...'
prefix. Without it,os.listdir()
might silently drop or ASCIIfy non-ASCII characters in your filenames, which then of course leads to invalid filenames. See also this question.This is stated in the docs for
os.listdir(path)
:出现错误是因为它试图从运行 python 程序的目录中打开文件;而不是文件所在的目录。
您需要为
open
提供文件的完整路径(包括目录名称)。The error appears because it is trying to open the file from the directory where you are running the python program; and not the directory where the file resides.
You need to give
open
the full path to your file (including the directory name).