如何从python中的目录路径读取文件

时间:2015-02-18 01:12:44

标签: python python-2.7

def serve_file(data,address):
    print sfile
    for filename in os.listdir(some/where/documents):
        print sfile
        with open(os.path.join(some/where/documents,data),"r"):
            s = fin.readline()
            while s != "":
                time.sleep(3)

serverSocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
serverSocket.bind(('127.0.0.27', 9090))
print "\nServer is listening..."

1 个答案:

答案 0 :(得分:3)

您是否在寻找从目录中获取文件列表的方法?你可能正在寻找一个" glob"。 glob获取与某些模式匹配的文件列表,其中也可能包含路径:

from glob import glob

# will be a list of all files ending in .txt
files_list = glob('/some/path/*.txt')

for fname in files_list:
    f = open( fname, 'r' )
    for line in f:
        print line

更多信息。在这里:https://docs.python.org/2/library/glob.html