简体   繁体   English

使用python将文件列表保存到文本文件中

[英]Save file list into text file using python

I would like to get the file name without its extension/suffix with split with specific character. 我想获取不带扩展名/后缀的文件名,并以特定字符分割。

There are so many jpg files in directory. 目录中有很多jpg文件。

for example, 例如,

A_list(B)_001.jpg A_list(B)_001.jpg

Stack_overflow_question_0.3.jpg Stack_overflow_question_0.3.jpg

... and hundreds files in some directory ...以及某个目录中的数百个文件

what I want is to get just the file NAMES without their extensions, like: 我想要的只是获得文件NAMES,没有其扩展名,例如:

A_list(B), 001 A_list(B),001

Stack_overflow_question, 0.3 Stack_overflow_question,0.3

but with below code, 但是用下面的代码,

import os

path = 'D:\HeadFirstPython\chapter3'
os.chdir(path)

data = open('temp.txt', 'w')

for file in os.listdir(path):
    if file.endswith('.jpg'):
        file = file.split('_')
        print(file, file=data)

data.close()

I got like below result. 我得到以下结果。

['A', 'list(B)', '001.jpg'] ['A','list(B)','001.jpg']

['Stack', 'overflow', 'question', '0.3.jpg'] [“堆栈”,“溢出”,“问题”,“ 0.3.jpg”]

Can this be done with less code? 可以用更少的代码来完成吗?

Thanks and kind regards, Tim 谢谢你,蒂姆

if file.endswith('.jpg'):
        file = file.rsplit('_',1)
        print file[0],
        print file[1].rsplit('.',1)[0]
        print(file, file=data)
import glob
import os

path = 'D:\HeadFirstPython\chapter3'
os.chdir(path)
with open("temp.txt","w") as f: # with automatically closes your files
   my_l = [x.replace(".jpg","").rsplit("_",1) for x in glob.glob("*.jpg")] # list of lists



with open("temp.txt", "w") as f:
    for x in glob.glob("*.jpg"):
        print x.replace(".jpg", "").rsplit("_", 1) # each list 

The output will look like: 输出将如下所示:

s = "Stack_overflow_question_0.3.jpg"

print s.replace(".jpg", "").rsplit("_", 1)
['Stack_overflow_question', '0.3']

To write to txt file without "," : 要写入不带"," txt文件:

with open("temp.txt", "w") as f:  # with automatically closes your files
    my_l = [x.replace(".jpg", "").rsplit("_", 1) for x in glob.glob("*.jpg")]
    for l in my_l:
        f.write(str(l).replace(",", ""))

Using "*.jpg" will search for any file ending with jpg . 使用"*.jpg"将搜索以jpg结尾的任何文件。 rsplit("_",1) will split on the rightmost _ and using 1 as maxsplit will only split once. rsplit("_",1)将在最右边的_拆分,并且使用1作为maxsplit只会拆分一次。 We simply replace the extension with str.replace . 我们只需将扩展名替换为str.replace

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM