"Python" Python reads all files under a folder __python

Source: Internet
Author: User
Os.listdir (path) is a list of the names of the files that are obtained under the path path.     Open (path) is the opening of a file.         ITER is the Python iterator. So read all the files under a folder as follows:
Import os
path = "D:/python34/news" #文件夹目录
files= os.listdir (path) #得到文件夹下的所有文件名称
s = [] for
file in file S: #遍历文件夹
     if not os.path.isdir (file): #判断是否是文件夹, is not a folder open
          f = open (path+ "/" +file); #打开文件
          iter_f = iter (f); Create an iterator
          str = "" For
          lines in Iter_f: #遍历文件, row by row, read text
              str = str + line
          s.append (str) #每个文件的文本存到list中
Print (s) #打印结果

You can also define the traversal of a folder as a function, and iterate over it if it is a folder. Then read all the files in the folder (including the files in the folder)
Author: Li Li Sign: don't have too many fantasies in life, but more action

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.