简体   繁体   English

Python 3.7 - 在文件夹中 all.txt 文件的每一行开头插入文件名

[英]Python 3.7 - insert filename at the start of every line in all .txt files in a folder

Python 3.7 - insert filename at the start of every line to all.txt files in a folder. Python 3.7 - 在文件夹中 all.txt 文件的每一行开头插入文件名。

I have a few differently named.txt files in a folder.我在一个文件夹中有几个不同命名的 .txt 文件。 I would like to insert the filename to the beginning of each line in each.txt file.我想将文件名插入到 each.txt 文件中每一行的开头。

So far all I've been able to do is insert numbers which I found from another post.到目前为止,我所能做的就是插入我从另一篇文章中找到的数字。 The below code works well for this, however I've been unable to find a way to insert the open filename:下面的代码适用于此,但是我一直无法找到插入打开文件名的方法:

import os

def add_numbers(filename):
    with open(filename, 'r') as readfile:
        data = readfile.readlines()
    with open(filename, 'w') as writefile:
        for i, line in enumerate(data):
            writefile.write('%d. %s' % (i + 1, line))

for path, _, filenames in os.walk('.'):
    for filename in filenames:
        add_numbers(os.path.join(path, filename))
import os

def add_numbers(filename):
    with open(filename, 'r') as readfile:
        data = readfile.readlines()
    with open(filename, 'w') as writefile:
        for i, line in enumerate(data):
            writefile.write('%s. %s' % (filename, line))

for path, _, filenames in os.walk('.'):
    for filename in filenames:
        add_numbers(os.path.join(path, filename))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Python将文件夹中的所有csv文件转换为txt - Python Convert all csv files in folder to txt 合并文件夹中每两个连续的txt文件-Python - Merge every two consecutive txt files in folder - Python 如何在具有不同名称的文件夹中加载 all.txt 文件 - Python - How to load all .txt files in a folder with separate names - Python 如何使用python和bs4读取和覆盖文件夹中的所有* .txt文件? - How to read and overwrite all *.txt files in a folder with python and bs4? python 打开相关文件夹中所有以.txt 结尾的文件 - python open all files ending with .txt in a relative folder 我在 1 个文件夹中有多个 txt 文件,我需要使用 python 将 txt 数据插入 MySql 表 - i have multiple txt files in 1 folder and I need to insert the txt data into MySql table using python 如何使用 Python 将文件夹中的 all.txt 文件和 append 其内容读取到 one.txt 文件中? - How to read all .txt files in a folder and append its contents into one .txt file, using Python? 将CSV转换为txt并使用Python每10个值开始换行 - Convert CSV to txt and start new line every 10 values using Python 如何按扩展名'filename_ext'.txt 附加文件并递归地添加到文件夹中的所有文件并将它们转换回原始扩展名 - How to append a file by extension 'filename_ext'.txt and recursively to all the files in a folder and convert them back into the original extension 在Python文件夹中的所有HTML文件中插入HTML标签 - Insert HTML tag in all HTML files in a folder in Python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM