python如何在一个文件夹中导入多个.txt文件以向每个.txt文件添加字符?

时间:2019-03-20 08:33:26

标签: python text directory

文件夹“ a”中有各种名称的文本文件。我想阅读所有这些文本文件,并将字母“ b”添加到每个文本文件。我该怎么办?

willTransition(transition) {
  if (this.controller.get('model.hasDirtyAttributes') && !confirm("Are you sure you want to abandon progress?")) {
    transition.abort();
  } else {
    this.controller.get('model').rollbackAttributes();
  }
}

3 个答案:

答案 0 :(得分:1)

将数据追加到文件:
-首先:获取文件夹 a 中的所有文件。
-第二:使用 .txt 查找扩展名。
-第三:打开它并执行一些操作(“追加”或“重写”)。

演示:

import os

# your .txt files dir
path = 'a'
# append data what you want
appendData = 'b'

fileNames = list(os.walk(path))[0][2]
fileNames.sort(key=len)
fileNums = len(fileNames)

# your dst file extension
fileExt = '.txt'
# # Extract extension from filename
# fileExt = os.path.splitext(fileNames[0])[1]

for fileName in fileNames:
    if fileName.endswith(fileExt):
        fileFullPath = os.path.join(path, fileName)
        with open(fileFullPath, 'a') as f:
            f.write(appendData)

答案 1 :(得分:0)

就像其他人说的那样,这是一个简单的问题,可以在Google上轻松找到。无论如何,这是操作方法:

from os import listdir
from os.path import isfile, isdir, join

files = [file for file in listdir("files") if isfile(join("files", file))]
        directories = [directory for directory in listdir("files") if isdir(join("files", directory))]

print(files)

for file_name in files:
    try:
        file = open("files/" + file_name, "a")
        file.write("b")
        file.close()
    except IOError as err:
        print("Could not open file because : ", err)

将“文件”替换为文件所在的目录或该目录的路径,例如“ directory0 / directory1 / directory_with_files”

答案 2 :(得分:0)

避免使用打开文件

f = open(input_dir, 'a')
f.close()

相反

with open(input_dir, 'a') as inputFile:
    Do something

您还想要什么

import os
import glob  # We will use this module to open only .txt files

path = 'your/path'

for filename in glob.glob(os.path.join(path, '*.txt'))
    with open(filename, 'a') as inputFile:
        inputFile.write('b')