【问题标题】:Creating files with names based on entries in txt file根据 txt 文件中的条目创建具有名称的文件
【发布时间】:2020-03-03 11:27:22
【问题描述】:
i = 1
with open("randomStuff\\test\\brief.txt") as textFile:
    lines = [line.split('\n') for line in textFile]
for row in lines:
    for elem in row:
        with open(elem + ".txt", "w") as newLetter:
            newLetter.writelines(elem)
            i += 1

我有一个带有名称的 txt 文件。我想创建具有以下名称的文件: 名字姓氏.txt 名称也出现在文件中。 目前它工作正常,但它在名为“.txt”的空文件上创建 有人能告诉我为什么吗?如果我是对的,问题应该出在循环中。

【问题讨论】:

  • brief.txt 可能在某处有一个空行。
  • 听起来你在文本文件中有一个空行,可能在最后?为什么不在循环遍历之前检查row 是否为空?注意,leave an empty line at the end of a text file 是相当标准的。
  • brief.txt 没有空行
  • for elem in row: 这是干什么用的? row 不是字符串吗?为什么你需要在不先拆分的情况下循环它?请提供您的文本文件示例
  • 那么lines[-1]的值是多少?

标签: python loops file


【解决方案1】:

添加 if 语句以防止在空行上创建文件

编辑

i = 1
with open("randomStuff\\test\\brief.txt") as textFile:
    lines = [line.split('\n') for line in textFile]
for row in lines:
    for elem in row:
        if elem == “”:
            continue
        with open(elem + ".txt", "w") as newLetter:
            newLetter.writelines(elem)
            i += 1

Continue 将跳转到下一个循环循环而不执行下面的代码

【讨论】:

  • 为什么不用if elem: with... 然后你就不需要continue了。
  • 感谢您的帮助。我不知道为什么,但我先试了一下。可能是一个小错误:D
  • 我就是这样。解决问题的方法无穷无尽,随心所欲。
【解决方案2】:

我不知道你为什么有这么多循环:

from pathlib import Path

text_file_content = Path("randomStuff/test/brief.txt").read_text().split_lines()
for line in text_file_content:
    if line:  # in case you have a new line at the end of your file, which you probably should
        with open(f"{line}.txt", "w") as new_letter:
            new_letter.writelines(line)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-17
    • 2022-10-05
    • 1970-01-01
    • 2021-10-07
    • 2016-01-05
    • 1970-01-01
    • 2021-11-30
    • 1970-01-01
    相关资源
    最近更新 更多