【问题标题】:Code in python that writes more than one text-file编写多个文本文件的python代码
【发布时间】:2021-03-07 12:52:02
【问题描述】:

我从一个代码开始,该代码旨在通过首先读取一个文本文件来编写许多文本文件。开始代码后问题的更多细节。

文本文件(我从名为 alphabet.txt 的 tex 文件中读取):

一个

b

c

:

d

e

f

:

g

h

我

:

我希望结果是这样的:

文件1:

一个

b

c

文件2:

d

e

f

文件3:

g

h

我

enter code here
 
with open('alphabet.txt', 'r') as f:
    a = []
    for i in f:
        i.split(':')
        a.append(a)

代码当然没有写完。问题:我不知道如何继续编写代码。是否可以编写文本文件并将它们放在特定文件夹中,也可以将它们重命名为“file1,file2...”而不用硬编码命名(直接从代码中)?

【问题讨论】:

    标签: python-3.x for-loop text-files file-writing file-read


    【解决方案1】:

    你可以用这样的东西来实现这个功能

    if __name__ == '__main__':
        with open('alphabet.txt', 'r') as f:
            split_alph = f.read().split(':\n')
            for i in range(len(split_alph)):
                x = open(f"file_{i}", "w")
                x.write(split_alph[i])
                x.close()
    

    根据 alphabet.txt 文件中是否存在最后一个 :,您必须使用以下命令关闭 split_alph 中的最后一个元素

    split_alph = f.read().split(':\n')[:-1]
    

    如果您对解决方案还有任何疑问,请告诉我。

    【讨论】:

    • 谢谢先生!几乎我想要的问题是文件确实看起来像:a b c
    • 只需从第 3 行中省略 .rstrip()。那么字符应该在彼此下方。并使用split(':\n') 而不是split(':') 删除第一个空行。
    • 您想编辑代码吗?我确实喜欢这样: split_alph = "".join([i.rstrip() for i in f]).split('\n:')[:-1] ,但它没有给我任何文件。珍惜你的时间! @TuDatTr
    • 我刚刚编辑了代码,新的解决方案没有很多不必要的位。
    【解决方案2】:
    file = open("C:/Users/ASUS/Desktop/tutl.py" , "r") # This is input File
    text = file.read()  # Reading The Content of The File.
    file.close()  # Closing The File
    splitted = text.split(":")  # Creating a List ,Containing strings of all Splitted part.
    
    destinationFolder = "path_to_Folder" # Replace this With Your Folder Path
    
    for x in range(len(splitted)):   # For loop for each parts
        
        newFile = open(destinationFolder + "/File"+str(x)+".txt" , "w")        # Creating a File for a part.
        newFile.write(splitted[x])                        # Writing the content
        newFile.close()                                   # Closing The File
    

    【讨论】:

    • 感谢您的宝贵时间,但是,使用此代码时出现错误
    • 对那个错误感到抱歉。我已经编辑了它。希望你会尝试。 :)
    • 谢谢先生!!!您知道在阅读文本文件后如何将文件发送到空文件夹吗?您能否在代码上编写 cmets 以便我更好地理解它?:)
    • 我已经做到了:)
    • 谢谢先生!!我非常感谢:)
    猜你喜欢
    • 2017-07-08
    • 1970-01-01
    • 1970-01-01
    • 2021-12-07
    • 2016-01-31
    • 1970-01-01
    • 1970-01-01
    • 2013-04-18
    • 2020-10-25
    相关资源
    最近更新 更多