繁体   English   中英

如何在python中写入和读取文件?

[英]How to write and read to a file in python?

到目前为止,我的代码如下:

restart = 'y'
while (True):
    sentence = input("What is your sentence?: ")
    sentence_split = sentence.split() 
    sentence2 = [0]
    print(sentence)
    for count, i in enumerate(sentence_split): 
        if sentence_split.count(i) < 2:
            sentence2.append(max(sentence2) + 1)
        else:
            sentence2.append(sentence_split.index(i) +1)
    sentence2.remove(0)
    print(sentence2)
    outfile = open("testing.txt", "wt")
    outfile.write(sentence)
    outfile.close()
    print (outfile)
    restart = input("would you like restart the programme y/n?").lower()
    if (restart == "n"):
            print ("programme terminated")
            break
    elif (restart == "y"):
        pass
    else:
        print ("Please enter y or n")

我需要知道该怎么做才能使我的程序打开一个文件,保存输入的句子以及重新创建该句子的数字,然后能够打印该文件。 (我猜这是阅读的部分)。 您可能会说,我对读取和写入文件一无所知,因此请写下您的答案,以便菜鸟可以理解。 同样,与文件相关的代码的一部分是在黑暗中从不同网站获取的完整信息,所以不要以为我对此有所了解。

基本上,您可以通过打开文件对象来创建文件对象,然后执行读取或写入操作

从文件中读取一行

#open("filename","mode")
outfile = open("testing.txt", "r")
outfile.readline(sentence)

从文件中读取所有行

for line in fileobject:
    print(line, end='')

使用python编写文件

outfile = open("testing.txt", "w")
outfile.write(sentence)

简而言之,要在python中读取文件,您需要以读取模式“打开”文件:

f = open("testing.txt", "r")

第二个参数“ r”表示我们打开文件进行读取。 在拥有文件对象“ f”之后,可以通过以下方式访问文件的内容:

content = f.read()

要使用python写入文件,您需要以写入模式(“ w”)或追加模式(“ a”)“打开”文件。 如果选择写入模式,则文件中的旧内容将丢失。 如果选择附加模式,新内容将被写入文件的末尾:

f = open("testing.txt", "w")

要将字符串s写入该文件,我们使用write命令:

f.write(s)

在您的情况下,可能类似于:

outfile = open("testing.txt", "a")
outfile.write(sentence)
outfile.close()

readfile = open("testing.txt", "r")
print (readfile.read())
readfile.close()

我建议您遵循cricket_007所指出的官方文档: https ://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM