使用python处理文件

想做一些简单的文件操作,用java太重量级,python是一个不错的选择。

有一个需求是将一个文件夹中所有的文件的内容提取出来分别填入excel的一个单元格中,

用os就可以对文件进行遍历,读文件信息

?





1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

import
os

# Get the all files & directories in the specified directory (path). 

def get_recursive_file_list(path): 

    current_files =
os.listdir(path) 

    all_files =
[] 

    for
file_name in
current_files: 

        full_file_name =
os.path.join(path, file_name) 

        all_files.append(full_file_name) 

  

        if
os.path.isdir(full_file_name): 

            next_level_files =
get_recursive_file_list(full_file_name) 

            all_files.extend(next_level_files) 

  

    return
all_files 

all_files=get_recursive_file_list(‘C:\Users\green_pasture\Desktop\korea\key_words‘)

for
filename in
all_files:

    print
filename

    f1=open(filename,‘r+‘)

    for
line1 in
f1:

      print
"\n"

          print
line1,

    f1.close

  但是遇到一个问题,IndentationError:unindent does not match any outer indentation
level,于是去查找了一下python的indentation:

http://www.secnetix.de/olli/Python/block_indentation.hawk

“关于python缩进的迷思”中说道:只有缩进层(即语句最左边)的空格是有意义的,并且跟缩进的确切数目无关,只和代码块的相对缩进有关。

同时,在你使用显式或者隐式的continue line时缩进会被忽略。

你可以把内层的代码同时写在一行,用分号隔开。如果要将他们写到不同的行,那么python会强制你使用它的indentation规则。在python中,缩进的层次和代码的逻辑结构是一致的。

不要把tab和space混在一起,通常,tab可以自动用8个空格来代替。

?





1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

import
os

# Get the all files & directories in the specified directory (path). 

def get_recursive_file_list(path): 

    current_files =
os.listdir(path) 

    all_files =
[] 

    for
file_name in
current_files: 

        full_file_name =
os.path.join(path, file_name) 

        all_files.append(full_file_name) 

  

        if
os.path.isdir(full_file_name): 

            next_level_files =
get_recursive_file_list(full_file_name) 

            all_files.extend(next_level_files) 

  

    return
all_files 

all_files=get_recursive_file_list(‘C:\Users\green_pasture\Desktop\korea\key_words‘)

for
filename in
all_files:

    print
filename

    f1=open(filename,‘r+‘)

    for
line1 in
f1:        print
line1,

  我将for里面的语句跟for写在了同一行,程序没有错误了。

接着我要把打印出来的文件内容写入到excel单元格当中。

可以使用xlsxWriter https://xlsxwriter.readthedocs.org/

xlwt http://www.python-excel.org/

openpyxl http://pythonhosted.org/openpyxl/

xlsxWriter文档挺全,就考虑用这个

samplecode是:

?





1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

##############################################################################

#

# A simple example of some of the features of the XlsxWriter Python module.

#

# Copyright 2013-2014, John McNamara, [email protected]

#

import
xlsxwriter

# Create an new Excel file and add a worksheet.

workbook =
xlsxwriter.Workbook(‘demo.xlsx‘)

worksheet =
workbook.add_worksheet()

# Widen the first column to make the text clearer.

worksheet.set_column(‘A:A‘, 20)

# Add a bold format to use to highlight cells.

bold =
workbook.add_format({‘bold‘: True})

# Write some simple text.

worksheet.write(‘A1‘, ‘Hello‘)

# Text with formatting.

worksheet.write(‘A2‘, ‘World‘, bold)

# Write some numbers, with row/column notation.

worksheet.write(2, 0, 123)

worksheet.write(3, 0, 123.456)

# Insert an image.

worksheet.insert_image(‘B5‘, ‘logo.png‘)

workbook.close()

  如何安装呢?可以使用pip
installer,我的python目录下C:\Python33\Scripts已经有pip.exe,把当前路径设置到path环境变量,在命令行执行pip
install XlsxWriter

出现了错误:

Fatal error in launcher: Unable to create process
using C:\Python33\Scripts\pip.exe install XlsxWriter。

改用从github下载,

?





1

2

3

4

$ git clone https://github.com/jmcnamara/XlsxWriter.git

$ cd XlsxWriter

$ sudo python setup.py install

  创建了一个测试程序:

?





1

2

3

4

5

6

7

8

import
xlsxwriter

workbook =
xlsxwriter.Workbook(‘hello.xlsx‘)

worksheet =
workbook.add_worksheet()

worksheet.write(‘A1‘, ‘Hello world‘)

workbook.close()

  测试成功。

?





1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

import
os

import
xlsxwriter

# Get the all files & directories in the specified directory (path). 

def get_recursive_file_list(path): 

    current_files =
os.listdir(path) 

    all_files =
[] 

    for
file_name in
current_files: 

        full_file_name =
os.path.join(path, file_name) 

        all_files.append(full_file_name) 

  

        if
os.path.isdir(full_file_name): 

            next_level_files =
get_recursive_file_list(full_file_name) 

            all_files.extend(next_level_files) 

  

    return
all_files 

workbook =
xlsxwriter.Workbook(‘keywords.xlsx‘)

worksheet =
workbook.add_worksheet()

all_files=get_recursive_file_list(‘C:\Users\green_pasture\Desktop\korea\key_words‘)

row=0

for
filename in
all_files:

    print
filename

    f1=open(filename,‘r+‘)

    keywords=""

    list=[]

    a="\n"

    for
line in
f1:     list.append(line),

    keywords=a.join(list)

    print
keywords

    worksheet.write(row,0, filename)

    worksheet.write(row,1,keywords.decode("utf-8"))

    row=row+1

workbook.close()

  

使用python处理文件,布布扣,bubuko.com

时间: 2024-08-25 23:50:34

使用python处理文件的相关文章

Python读写文件

Python读写文件1.open使用open打开文件后一定要记得调用文件对象的close()方法.比如可以用try/finally语句来确保最后能关闭文件. file_object = open('thefile.txt')try:     all_the_text = file_object.read( )finally:     file_object.close( ) 注:不能把open语句放在try块里,因为当打开文件出现异常时,文件对象file_object无法执行close()方法.

解决Python读取文件时出现UnicodeDecodeError: 'gbk' codec can't decode byte...

用Python在读取某个html文件时会遇到下面问题: 出问题的代码: 1 if __name__ == '__main__': 2 fileHandler = open('../report.html', mode='r') 3 4 report_lines = fileHandler.readlines() 5 for line in report_lines: 6 print(line.rstrip()) 修改方式是在open方法指定参数encoding='UTF-8': if __nam

将Python脚本文件包装成可执行文件

将Python脚本文件包装成可执行文件,其目的有二: 一则: 不需要依赖Python编译器就可以运行软件 二则: 不想让自己的源码公布出去 常用的工具有: py2exe.cx_freeze等 [工具:py2exe] 安装py2exe 安装该工具很简单: 只需要从官方网站:http://www.py2exe.org/下载与版本对应的安装程序,点击下一步即可完成安装. 安装后,执行import py2exe,不报错则表示安装成功! >>> import py2exe >>>

[改]在windows右键菜单中加入“新建Python File文件”并创建模板

1.首先写好模板文件,随便保存在一个地方,比如我是"D:\Python27\foo.py"; 2.打开注册表(regedit),找到 [HKEY_CLASSES_ROOT] -> [.py] (没有的话,自己新建项.py); 3.在 [.py] 下新建项 [ShellNew] (已经有的话就删掉重建); 4.在 [ShellNew] 下新建 字符串值 ,名称为 FileName ,键值为模板文件的绝对路径,比如我的是 D:\Python27\foo.py ; 在右键新建菜单中就会

python之文件对象

防伪码忘情公子著 文件对象是用来访问文件系统接口所对应的数据的 文件系统是OS用于明确磁盘或分区上的文件的方法和数据结构-即在磁盘上组织文件的方法 计算机文件或称文件.电脑档案.档案是存储在某种长期储存设备或临时存储设备中的一段数据流并且归属于计算机文件系统管理之下 概括来讲 文件是计算机中由OS管理的具有名字的存储区域 在Linux系统上文件被看做是字节序列 要想把数据存储到文件中有一个前提那就是必须序列化非序列化的数据是不能简单的存储在文件系统中的文件中的 对于python来说文件对象不仅可

Python open文件读写模式说明

对于Python打开文件的模式,总是记不住,这次在博客里记录一下 r+: Open for reading and writing.  The stream is positioned  at  the beginning of the file. w+:Open for reading and writing.  The file is created  if  it  does not  exist, otherwise it is truncated.  The stream is pos

从自动生成.h的头文件集合和类声明集合到用python读写文件

最近在用python自动生成c++的类.因为这些类会根据需求不同产生不同的类,所以需要用python自动生成.由于会产生大量的类,而且这些类是变化的.所以如果是在某个.h中要用include来加载这些类,会累死人的.所以用python来生成这些类的头文件引用和类的类名声明 先看例子,再聊python的读写文件的代码 在聊聊我的python代码 ------------------------> 好吧.上面的图就是面临的需求 下面来聊聊从网上找的读写文件的python代码吧.csdn的一个博主写的

python之文件操作-复制、剪切、删除等

下面是把sourceDir文件夹下的以.JPG结尾的文件全部复制到targetDir文件夹下: <span style="font-size:18px;">>>>import os >>> import os.path >>> import shutil >>> def copyFiles(sourceDir,targetDir): for files in os.listdir(sourceDir):

Python Selenium 文件上传(二)

今天补充一种文件上传的方法 主要是因为工作中使用SendKeys方法不稳定,具体方法见: Python Selenium 文件上传(一) 这种方法直接通过命令行执行脚本时没有问题,可以成功上传,但是如果通过saltstack 远程控制执行时,SendKeys就定位不到窗口了. 所以采用这种新的方式来实现文件上传功能,并完美的解决了这个问题. 具体操作步骤如下: 1.下载工具 AutoIt及使用 AutoIt目前最新是v3版本,这是一个使用类似BASIC脚本语言的免费软件,它设计用于Windows

Python Selenium 文件上传(一)

昨天写了Web 文件下载的ui自动化,下载之后,今天就要写web 文件上传的功能了. 当然从折腾了俩小时才上传成功.下面写一下自己操作的步骤 首先网上说的有很多方法 如 input 标签的最好做了,直接定位到元素,然后再sendKeys("value")即可 <input id="file_name" class="text-1 w255" type="text" readonly="" value=