Introduce the method of Python to read the specified suffix file in the specified directory and save it as docx

Y2J
Release: 2017-05-02 15:52:03
Original
1740 people have browsed it

This article mainly introduces Python to read the specified suffix file in the specified directory and save it as docx. Friends who need it can refer to it

Recently there is a strange request to apply for a patent for N lines of code in the project. Of course, as a programmer, you cannot copy and paste and use code to solve it. .

Use python-docx to read and write docx filesThe environment uses python3.6.0

First install python-docx with pip

pip install python-docx

Then the following is the script modification directory. By default, the src folder in the script running directory is taken.

Read all files with the .cs suffix and save them as docx.


One thing to note is that if there is Chinese in the file, please use vscode or other editors to open it in utf-8 format to see if there are any garbled characters. Each time a file is processed, there will be a print output. When you see only - --When start has no end, you can find the file to see if there is any situation mentioned above. After modification, save and re-execute until all executions are completed. Save the docx file

code

# -- coding: UTF-8 --
# Created by luody on 2017/4/7.
import os
from docx import Document
saveFile = os.getcwd() + "/code.docx"
mypath = os.getcwd() + "/src"
doc = Document()
doc.add_heading("代码文档", 0)
p = doc.add_paragraph('服务端代码,使用语言')
p.add_run('C#,SQL').bold = True
lineNum = 0
for root, dirs, files in os.walk(mypath):
  for filespath in files:
    if (filespath.endswith('.cs')):
      doc.add_heading(filespath, level=1)
      codePage = ''
      print(filespath+' ---- start')
      for line in open(os.path.join(root, filespath), encoding="utf-8"):
        codePage += line
        lineNum += 1
      print(filespath+' ---- end')
      doc.add_paragraph(codePage, style='IntenseQuote')
      doc.add_page_break()
p = doc.add_paragraph(u'总行数:')
p.add_run(str(lineNum)).bold = True
doc.save('code.docx')
print(lineNum)
Copy after login

The above is the detailed content of Introduce the method of Python to read the specified suffix file in the specified directory and save it as docx. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template