试图在python中只打印一行文本文档

时间:2012-11-04 21:56:28

标签: python file text

我正在编写一个程序,允许你在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()

3 个答案:

答案 0 :(得分: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]

答案 1 :(得分: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

答案 2 :(得分:0)

由于我不使用' def'功能,但这会打印出您要打印的行

import os.path

bars = open('bars.txt', 'r')
first_line = bars.readlines()
length = len(first_line)
bars.close()
print(first_line[2])