简体   繁体   English

将文本文件拆分为单独的文件,并将子字符串保存在文件名中; 蟒蛇

[英]Splitting text file to separate files, and saving substrings in filenames; Python

Searched for answers extensively, and have made a number of unsuccessful attempts, but can't seem to figure out how to do the following: 广泛搜索答案,并进行了一些不成功的尝试,但似乎无法弄清楚如何执行以下操作:

I'm using the following python code to save each line of a text file as a separate file: 我正在使用以下python代码将文本文件的每一行保存为单独的文件:

with open("filename.txt") as sourcefile:
    for i, line in enumerate(sourcefile):
        with open("filename{}.txt".format(str(i+1)), "w") as txtfile:
            txtfile.write(line)

That creates filenames as follows: filename1.txt, filename2.txt, filename3.txt. 这将创建文件名,如下所示:filename1.txt,filename2.txt,filename3.txt。 What I would like to do is insert a substring of the first 30 characters from each line of text in the separate filename for each line's file. 我想要做的是在每行文件的单独文件名中插入每行文本的前30个字符的子字符串。

For example, assume that the first line in the original file is the sentence "I would like to get a pizza for dinner tonight." 例如,假设原始文件中的第一行是句子“我想今晚要吃披萨。” I'd like the filename for that individual line to be saved as "filename I would like to get a pizza fo.txt." 我希望将该行的文件名保存为“我希望获得披萨fo.txt的文件名”。

Any help is greatly appreciated. 任何帮助是极大的赞赏。

If I understood correctly, you want to name each file with the first 30 characters of each line . 如果我理解正确,您希望使用每line的前30个字符命名每个文件。 To achieve that, you can use line[0:29] , which means "cut the string line between characters 0 and 29 ([start:end]). 要实现这一点,您可以使用line[0:29] ,这意味着“剪切字符0和29之间的字符串line ([start:end])。

Sample: 样品:

with open("filename.txt") as sourcefile:
    for i, line in enumerate(sourcefile):
        with open("filename {}.txt".format(line[0:29]), "w") as txtfile:
            txtfile.write(line)

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

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