Board logo

标题: [文本处理] 【已解决】批处理如何实现批量将若干字符串依次循环插入到txt文本的每行行首? [打印本页]

作者: wzf1024    时间: 2016-4-15 21:14     标题: 【已解决】批处理如何实现批量将若干字符串依次循环插入到txt文本的每行行首?

本帖最后由 wzf1024 于 2016-4-16 02:21 编辑

有很多txt,包括子文件夹,需要在每个txt行首循环插入指定的若干字符,如:
原文内容……
原文内容……
原文内容……
原文内容……
原文内容……
原文内容……
原文内容……
原文内容……
指定变量word=米诺,波普,铅笔,小胖……
将变量word的接受的字符一个一个插入txt行首,插完又重新开始:
米诺#原文内容……
波普#原文内容……
铅笔#原文内容……
小胖#原文内容……
米诺#原文内容……
波普#原文内容……
铅笔#原文内容……
小胖#原文内容……
=======================
大侠帮忙啊,又有想不通的难题了
作者: codegay    时间: 2016-4-15 21:23

不出意料的话,你也会在这个论坛连续提问上好几年。。。
作者: CrLf    时间: 2016-4-15 22:19

回复 2# codegay


    怎么能跟大你 24 天的前辈说这么没礼貌的话
作者: pcl_test    时间: 2016-4-15 22:21

本帖最后由 pcl_test 于 2016-4-15 22:23 编辑

举个栗子
  1. @echo off
  2. setlocal enabledelayedexpansion
  3. for %%a in (a b c) do set /a n+=1&set "#!n!=%%a"
  4. for /f "delims=" %%a in ('more +9 "%~f0"') do (
  5.     set /a m+=1
  6.     call echo;%%#!m!%%#%%a
  7.     if !m! equ !n! set m=
  8. )
  9. pause&exit
  10. 1
  11. 2
  12. 3
  13. 4
  14. 5
  15. 6
  16. 7
  17. 8
  18. 9
  19. 10
  20. 11
复制代码

作者: codegay    时间: 2016-4-15 22:56

  1. """
  2. txt文件首行前加上字符.py
  3. 2016年4月15日 22:02:34 codegay
  4. """
  5. from itertools import cycle
  6. from subprocess import getoutput
  7. from itertools import zip_longest
  8. words=["米诺","波普","铅笔","小胖"]
  9. txt=getoutput('cmd /c "dir /s /b /a:-d *.txt"').split("\n")
  10. for word,files in zip(cycle(words),txt):
  11.     with open(files,"r+") as f:
  12.         line=f.readlines()
  13.         if "#" not in line[0]:
  14.             line=[word+"#"]+line
  15.             f.seek(0)
  16.             f.writelines(line)
复制代码

作者: wzf1024    时间: 2016-4-15 23:24

本帖最后由 wzf1024 于 2016-4-15 23:25 编辑

回复 5# codegay


   额~~大侠,是行首不是首行,是每个txt的每一行循环插入,不是一个txt只插入首行,并且每个txt从第一个字符开始插入,就是每个txt都是一个独立循环
作者: wzf1024    时间: 2016-4-15 23:31

回复 2# codegay


    能者为师,多谢指导!
作者: wzf1024    时间: 2016-4-16 02:09

回复 5# codegay


    在pcl_test的代码基础上修改的,达到目的,谢谢大侠的栗子:
  1. @echo off
  2. setlocal enabledelayedexpansion
  3. for %%a in (a b c d e) do set /a n+=1&set "#!n!=%%a"
  4. for /f "delims=" %%i in ('dir /b/s *.txt') do (
  5. set m=0
  6. (for /f "tokens=*" %%j in ('type "%%i"') do (
  7. if !m! equ !n! set m=
  8.     set /a m+=1
  9. call echo;%%#!m!%%#%%%j))>$
  10. move $ "%%i"
  11. )
  12. pause&exit
复制代码

作者: wzf1024    时间: 2016-4-16 02:11

回复 4# pcl_test


    谢谢大侠的栗子!




欢迎光临 批处理之家 (http://bbs.bathome.net/) Powered by Discuz! 7.2