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

2024-09-25 20:16:08 发布

您现在位置: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")

我需要知道怎么做,以便我的程序打开一个文件,保存输入的句子和数字,重新创建句子,然后能够打印文件。(我猜这是阅读部分)。正如你可能知道的,我对文件的读写一无所知,所以请写下你的答案,这样一个傻瓜就可以理解了。还有一部分的代码,是有关文件是一个完整的刺刀在黑暗中,从不同的网站,所以不要认为我有这方面的知识。你知道吗


Tags: 文件代码inputifcountelsesentenceoutfile
2条回答

简单地说,要用python读取文件,需要以读取模式“打开”文件:

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

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

content = f.read()

要用python编写文件,您需要以write模式(“w”)或append模式(“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所指出的官方文档:https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files

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

从文件中读取行

#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)

相关问题 更多 >