第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會有你想問的

如何打開文件夾中的每個(gè)文件?

如何打開文件夾中的每個(gè)文件?

慕村225694 2019-11-05 16:30:48
我有一個(gè)python腳本parse.py,該腳本在腳本中打開一個(gè)文件,例如file1,然后執(zhí)行一些操作,可能會打印出字符總數(shù)。filename = 'file1'f = open(filename, 'r')content = f.read()print filename, len(content)現(xiàn)在,我正在使用stdout將結(jié)果定向到我的輸出文件-輸出python parse.py >> output但是,我不想按文件手動(dòng)處理此文件,有沒有辦法自動(dòng)處理每個(gè)文件?喜歡ls | awk '{print}' | python parse.py >> output 然后問題是如何從standardin中讀取文件名?還是已經(jīng)有一些內(nèi)置功能可以輕松執(zhí)行l(wèi)s和此類工作?謝謝!
查看完整描述

3 回答

?
拉莫斯之舞

TA貢獻(xiàn)1820條經(jīng)驗(yàn) 獲得超10個(gè)贊

你應(yīng)該嘗試使用os.walk


yourpath = 'path'


import os

for root, dirs, files in os.walk(yourpath, topdown=False):

    for name in files:

        print(os.path.join(root, name))

        stuff

    for name in dirs:

        print(os.path.join(root, name))

        stuff


查看完整回答
反對 回復(fù) 2019-11-05
?
猛跑小豬

TA貢獻(xiàn)1858條經(jīng)驗(yàn) 獲得超8個(gè)贊

實(shí)際上,您可以只使用os模塊來完成這兩項(xiàng):


列出文件夾中的所有文件

按文件類型,文件名等對文件進(jìn)行排序

這是一個(gè)簡單的例子:

import os #os module imported here

location = os.getcwd() # get present working directory location here

counter = 0 #keep a count of all files found

csvfiles = [] #list to store all csv files found at location

filebeginwithhello = [] # list to keep all files that begin with 'hello'

otherfiles = [] #list to keep any other file that do not match the criteria


for file in os.listdir(location):

    try:

        if file.endswith(".csv"):

            print "csv file found:\t", file

            csvfiles.append(str(file))

            counter = counter+1


        elif file.startswith("hello") and file.endswith(".csv"): #because some files may start with hello and also be a csv file

            print "csv file found:\t", file

            csvfiles.append(str(file))

            counter = counter+1


        elif file.startswith("hello"):

            print "hello files found: \t", file

            filebeginwithhello.append(file)

            counter = counter+1


        else:

            otherfiles.append(file)

            counter = counter+1

    except Exception as e:

        raise e

        print "No files found here!"


print "Total files found:\t", counter

現(xiàn)在,您不僅列出了文件夾中的所有文件,而且(可選)按起始名稱,文件類型等對它們進(jìn)行了排序。剛才遍歷每個(gè)列表并做您的工作。


查看完整回答
反對 回復(fù) 2019-11-05
  • 3 回答
  • 0 關(guān)注
  • 581 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號