【问题标题】:How to open and edit a txt file in a while loop?如何在while循环中打开和编辑txt文件?
【发布时间】:2021-12-20 10:49:54
【问题描述】:

首先,我对 python 很陌生,我参加的这门大学课程对我没有帮助,所以提前抱歉。

我有一个带有书名的文本文档。我需要让用户输入一个选项。每个选项都与显示文本文档、编辑文本文档或只是停止程序同时进行。我有最后一个 一。我可以循环显示它。但是,如果我尝试循环执行它,它什么也没做,没有错误,什么都没有。

f = open("Books.txt")
for line in f:
    print (line)

inp = ()
while inp != 3:
    print("1 - Display, 2 - Add, 3 - Exit")
    inp = input("Please select an option.")
    inp = int(inp)
if inp == 1:
    print (f)

【问题讨论】:

  • 能否请您重新表述一下您的问题以便更清楚?
  • 是的,再给我一次抱歉

标签: python python-3.x txt


【解决方案1】:

您可以通过对文件对象 (f) 使用 tell()seek() 方法来做到这一点

这是它的代码

f = open("Books.txt", "a+")
inp = 0

while inp != 3:
    print("1 - Display, 2 - Add, 3 - Exit")
    inp = input("Please select an option.")
    inp = int(inp)
    if inp == 1:
        if f.tell() != 0:
            f.seek(0)
        for line in f:
            if line.strip():
                print (line.strip())
    elif inp == 2:
        book = input("What is your book name? ")
        f.writelines(["\n"+book])
   
f.close()

this的输出如下

1 - Display, 2 - Add, 3 - Exit
Please select an option.1
HELLO
WORLD
TEST
1 - Display, 2 - Add, 3 - Exit
Please select an option.2
What is your book name? Test2
1 - Display, 2 - Add, 3 - Exit
Please select an option.1
HELLO
WORLD
TEST
Test2
1 - Display, 2 - Add, 3 - Exit
Please select an option.3

代码解释如下

  1. 以具有可读访问权限的附加模式打开文件 (https://docs.python.org/3/library/functions.html#open)

  2. 在这种情况下,文件光标将位于 EOF(文件结尾),因此您可以轻松地将新文本附加到文件中

  3. 当输入为1 时,我们首先使用tell() 检查光标位置,它返回读取字节数的整数值,如果它不在起始位置。我们使用seek(0) (https://docs.python.org/3/tutorial/inputoutput.html) 将光标移动到文件的开头

  4. 由于可能存在仅包含换行符的空行,我们可以在打印时过滤掉它们,然后通过再次使用字符串上的strip() 方法去除白色字符来打印文本,因为打印函数会自动添加新的行字符

  5. 要写一行,我们需要传递一个新字符(当然是行分隔符),然后是书的输入名称

【讨论】:

  • 它不会让我。我太新了。对不起。
  • @AidenLumpkins 没问题。我看到您从我的答案中删除了接受的标签。你能帮我修一下吗?哪里坏了?
  • 它没有坏掉。我刚刚重新做了标签。希望这次能坚持下去。
【解决方案2】:
f = open("Books.txt", "r+")
inp = 0

while inp != 3:
    print("1 - Display, 2 - Add, 3 - Exit")
    inp = input("Please select an option.")
    inp = int(inp)
    if inp == 1:
        for line in f:
            print (line)
    elif inp == 2:
        book = input("What is your book name? ")
        f.writelines(["\n"+book])
   
f.close()
exit()

【讨论】:

  • 非常感谢。我非常感谢您的帮助。
  • @LarrytheLlama 该文件没有写权限,因此当用户输入 2 时它将失败
  • @tbhaxor 我看到了。我想我修好了。感谢您的帮助。
猜你喜欢
  • 2023-01-20
  • 1970-01-01
  • 2021-10-23
  • 1970-01-01
  • 2016-01-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多