Pythonのコアプログラミング:Pythonのファイルとフォルダの方法が存在するかどうかを判断します

この記事はPythonのファイルやフォルダの存在を決定する方法について説明し、本論文でも、ファイルやディレクトリかどうかos.path.lexistの役割を決定する方法を説明し、FTPその他のコンテンツがあるかどうかを判断するために、ファイルまたはディレクトリは、あなたが必要です友人は以下を参照することができます

>>> import os
>>> os.path.exists('d:/assist')
True
>>> os.path.exists('d:/assist/getTeacherList.py')
True
>>> os.path.isfile('d:/assist')
False
>>> os.path.isfile('d:/assist/getTeacherList.py')
True
>>> os.makedirs('d:/assist/set')
>>> os.path.exists('d:/assist/set')
True

二つは、Pythonは、ファイルが存在するかどうかを確認します

import os
 
filename = r'/home/tim/workspace/test.txt'
if os.path.exists(filename):
    message = 'OK, the "%s" file exists.'
else:
    message = "Sorry, I cannot find the "%s" file."
print message % filename

第三には、どのようにPythonのファイルがあるかどうかを判断します

使用os.path.exists()メソッドは、直接ファイルが存在するかどうかを決定することができます。

コードは以下の通りであります:

>>> import os
>>> os.path.exists(r'C:\1.TXT')
False
>>>

戻り値がTrueであった場合、Falseが全く存在しない場合に返される
4、pythonのフォルダがあるかどうかを判断します

$ python
Python 2.7.3 (default, Jan  2 2013, 16:53:07)
[GCC 4.7.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>>
>>>
>>> tobecheckdir = r'/home/tim/workspace'
>>> os.path.isdir(tobecheckdir)
True
>>>

ファイブは、pythonのファイルをチェックし、存在するファイルパスかどうか

ファイルを書き込む前に、通常のファイルパスを書き込むことができることを確認する必要があります。

from os import path, access, R_OK  # W_OK for write permission.
PATH='./file.txt'

if path.exists(PATH) and path.isfile(PATH) and access(PATH, R_OK):
    print "File exists and is readable"
else:
    print "Either file is missing or is not readable"

また、次の方法で達成することができます:

def file_exists(filename):
    try:
        with open(filename) as f:
            return True
    except IOError:
        return False

六は、Pythonのファイルやフォルダが存在するかどうかを判断します

import os
os.path.isfile('test.txt') #如果不存在就返回False
os.path.exists(directory) #如果目录不存在就返回False

七、os.path.lexist

そこos.path.lexists(パス)
壊れたリンクファイルのは、Trueを返します。

八、PythonのFTPフォルダが存在するかどうかを判断します

どのようにPythonの判定フォルダが存在しますか?ユーザーの大半は答えを与える:
それは上のライブラリftpの使用は、以下のコアPythonプログラミングの例です。

>>> from ftplib import FTP
>>> f = FTP('ftp.python.org')
>>> f.login('anonymous', '[email protected]')
'230 Guest login ok, access restrictions apply.'
>>> f.dir()

そのようなファイル内のDIR結果が存在しません。
あるいは、次のように:

try:
f.retrbinary('RETR %s' % FILE,open(FILE, 'wb').write)
except ftplib.error_perm:
print 'ERROR: cannot read file "%s"' % FILE 40 os.unlink(FILE)

あなたはこのファイルを読み取るだけでなく、存在しないとみなすことはできません。
お勧めのpython学習サイトをプログラムで学ぶことです何歳見て、!基本的なPythonスクリプト、爬虫類、ジャンゴ、データマイニング、技術をプログラミング、仕事の経験だけでなく、小型のpythonパートナーのシニア入念な研究から戦闘にゼロベースの情報のプロジェクトを仕上げ!毎日、Pythonプログラマは、いくつかの学習方法と注意を払うに小さな細部への必要性を共有し、技術のタイミングを説明し、

发布了51 篇原创文章 · 获赞 122 · 访问量 8万+

おすすめ

転載: blog.csdn.net/haoxun03/article/details/104348620