Python批处理附加到单个目录中特定类型的文件

2024-09-28 04:23:54 发布

您现在位置:Python中文网/ 问答频道 /正文

抱歉,如果这已经演示了怎么做。在

我正在尝试用Python批处理一些文件

我需要在文件夹中的html文件列表的末尾附加一个字符串。在

所以步骤是:

  1. 打开文件夹中的所有文件
  2. 附加字符串-在每个文件的底部添加字符串)
  3. 关闭文件

我已经看过一些关于堆栈交换的解决方案,但是我一直遇到语法错误。在

有段时间没用python了,所以有点生疏了。在

import os
for file in os.listdir("c:\Users\a\Desktop\New"):
if file.endswith(".html"):
   appendString = "\ add this string to end of file"
   appendFile.write = (appendString)
   apendFile.close()

我相信这很简单。在

请告知多谢!在

**很抱歉我的代码有错误,因为我打开了很多文件,这是一个漫长的一天!在

编辑: 而且文件中已经有需要保留的内容。 我只想在每个文件的底部添加示例文本。在


Tags: 文件字符串import文件夹列表堆栈oshtml
3条回答

从使用file到{},但是代码没有显示您已经设置了它。在

import os

for file in os.listdir("c:\\Users\\a\\Desktop\\New"):
    if file.endswith(".html"):
        appendString = "\ add this string to end of file"
        with open(file, 'a') as appendFile:
            appendFile.write(appendString)

Docs link for file I/O

你的代码缺失了一些东西(缩进,appendFile的定义,加上打字错误)。在

关于:

import os
for filename in os.listdir("c:\Users\a\Desktop\New"): # filename is a string
    if filename.endswith(".html"): # notice the indent
        appendFile = open(filename, 'a') # file object, notice 'a' mode
        appendString = "\ add this string to end of file" # could be done out of the loop if constant
        appendFile.write(appendString)
        appendFile.close()

要点:最好不要使用file作为变量名,因为它也是python2.7中内置函数的名称(类似于open)。在

您还可以使用with构造来完成结束操作(参见Celeo的回答)。在

glob提供与给定glob表达式匹配的文件的路径列表。在您的例子中,您需要在某个目录中以.html(即*.html)结尾的任何内容。在

一旦您获得了这些文件路径,那么向它们添加文本非常简单

import glob
import os

dirpath = 'directory/with/html/files'
appendStr = 'this string will be appended'

for fpath in glob.glob(os.path.join(dirpath, "*.html")):
    with open(fpath, 'a') as outfile:
        outfile.write(appendStr)

相关问题 更多 >

    热门问题