2016-11-12 75 views
0

下面是我的代码看起来像至今:如何在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") 

我需要知道做什么,这样我的程序打开文件,节省了句输入,而且重建了一句,然后将数字能够打印文件。 (即时猜测这是阅读部分)。正如你可能知道的那样,我对文件的阅读和写作一无所知,所以请写下你的答案,这样小白就能理解。此外,与文件相关的代码的一部分是在黑暗中的完整刺伤,并从不同的网站采取,所以不要认为我有这方面的知识。

+1

不要从随机的网站,使用[官方教程](https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files) –

+0

无论如何,你可能想要在while循环之前打开文件,然后关闭它们。 –

回答

2

基本上,你打开它创建一个文件对象,然后不要读或写操作

从文件

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

看来,OP使用的是Python 3.x,所以使用上下文管理器“with”将是打开文件并关闭它的更好选择。 –

0

把它简单,读取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