-1

我正在制作一个程序,可以让您在 python 中编辑或阅读文本文档,但我还没有完成,我被困在阅读部分。我希望它只打印一行,而我正在为如何做到这一点画一个空白。读取部分在“def read():”中

def menu():
    print("What would you like to do?")
    print("\n(1) Write new text")
    print("(2) Read line 3")
    choice = float(input())
    if choice == 1:
        write()
    elif choice == 2:
        read()

def read():
    with open('test.txt', 'r') as read:
        print()

def write():
    print("\nType the full name of the file you wish to write in.")
    file1 = input().strip()
    with open(file1, "a") as add:
        print("What do you want to write?")
        text = input()
        add.write("\n"+ text)

menu()
4

3 回答 3

2
def read():
    with open('test.txt', 'r') as f:
        for line in f:
            print(line)

编辑:

def read():
    with open('test.txt', 'r') as f:
        lines = f.readlines()
        print lines[1]
于 2012-11-04T21:57:53.843 回答
1

您可以将该文件用作可迭代文件,并对其进行循环,或者您可以调用.next()它以一次推进一行。

如果您需要阅读 1 条特定的行,这意味着您可以在使用.next()调用之前跳过这些行:

def read():
    with open('test.txt', 'r') as f:
        for _ in range(2):
            f.next()  # skip lines

        print(f.next())  # print the 3rd line
于 2012-11-04T22:06:03.167 回答
0

因为我不使用'def'函数,所以我很晚才发现我的,但这会打印出你想要打印的行

import os.path

bars = open('bars.txt', 'r')
first_line = bars.readlines()
length = len(first_line)
bars.close()
print(first_line[2])
于 2014-03-05T21:43:54.533 回答