wideband 发表于 2022-2-11 07:27:16

改名格式:据文件夹内文件名前4列数字查询 txt文件名

比如E 盘文件夹 sixmp3 有文件夹内有文件:
3348.mp3
3349.mp3
3350.mp3
3351.mp3
3352.mp3
3353.mp3

改名:据文件夹内文件名前4列数字查询 txt文件名:11.txt文本文件内容为:

3348观刈麦 唐 白居易
3349钱塘湖春行 唐 白居易
3350雁门太守行 唐 李贺
3351赤壁 唐 杜牧
3352泊秦淮 唐 杜牧
3353夜雨寄北 唐 李商隐

比如对于文件名:3348.mp3,   11.txt内第一行 信息是:3348观刈麦 唐 白居易
那么文件名就改为: 3348观刈麦 唐 白居易

现在 遇到问题:
因为 txt是 用识图软件获取的文件名,数字格式不是完全统一,导致手动改名都会出现如下错误:

文件名不能包含下列任何字符:

\/:*?",<>|

但是,txt各行的文件名,虽然识图软件识别的,但是直观看,并没有这些字符,如何处理比较合适?谢谢!

wideband 发表于 2022-2-11 08:10:42

可以复制11.txt 到excel, 然后再copy 出来 12.txt, 此时可以直接复制修改文件名。

但是,是否可以在程序里,直接格式化 11.txt 各行内容呢?

大马强 发表于 2022-2-11 08:19:08

文件名不能包含下列任何字符:

\/:*?",<>|
如果只是单单这些字符,我认为可以用先读到一个变量中,再用字符串的replace方法将其替换

大马强 发表于 2022-2-11 08:23:16

text = text.replace("\", '').replace("/", '').replace(
            ":", '').replace("*", '').replace("?", '').replace(
            '"', '').replace(",", '').replace("<", '').replace(
            ">", '')

wideband 发表于 2022-2-11 10:49:02

读取txt文件每一行数据生成列表:
txtline=[]
with open('11.txt','r') as f:
    lines = f.readlines()
    for line in lines:
      #print(line.strip())
      txtline.append(line.strip())
print(txtline)

1      255   547
12    54       45
78    89       56
44    11       23

【Python-数据读取】读取txt文件每一行数据生成列表
读出的数据dataMat 是一个由每行前两列组成的二维数组,labelMat 是由每行的最后一列组成的列表

file = open('11.txt')
dataMat=[]
labelMat=[]
for line in file.read.readlines():
    curLine=line.strip().split("\t")
    floatLine=map(float,curLine)#转换float
    dataMat.append(floatLine)
    labelMat.append(floatLine[-1])

print 'dataMat:',dataMat
print 'labelMat:',labelMat
print np.shape(dataMat)
print np.array(dataMat)

wideband 发表于 2022-2-11 11:10:55

python逐行读取txt文件时出现多余空行的问题

大马强 发表于 2022-2-11 11:51:47

wideband 发表于 2022-2-11 11:10
python逐行读取txt文件时出现多余空行的问题

是在末尾吗?

wideband 发表于 2022-2-11 12:13:00

谢谢大马强,末尾空行没有了,fs5, fs6 打印结果如下:

['3386.mp3', '3387.mp3',.....]

['3386方明-氓 诗经 国风卫风.mp3', '8387方明-离骚(节选) 战国 屈原.mp3',.....]

import os
txtline=[]
with open('11.txt','r') as f:
    lines = f.readlines()
    for line in lines:
      #print(line.strip())
      txtline.append(line.strip())

fn55 = []
fn66 = []

dirname5 = os.path.join('E:', '\sixmp3')
fs5 =

fs6 = txtline
print(fs5)
print(fs6)

怎么把文件夹内文件名字3386.mp3 更名为:3386方明-氓 诗经 国风卫风.mp3?

wideband 发表于 2022-2-11 16:09:22

用名字创建文件就可以了。

import os
txtline=[]
with open('11.txt','r') as f:
    lines = f.readlines()
    for line in lines:
      txtline.append(line.strip())

print(txtline)
for name in txtline:
    file1 = open(name,'w')
页: [1]
查看完整版本: 改名格式:据文件夹内文件名前4列数字查询 txt文件名