简体   繁体   中英

How to write and read to a file in python?

Below is what my code looks like so far:

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

I need to know what to do so that my programme opens a file, saves the sentence entered and the numbers that recreate the sentence and then be able print the file. (im guessing this is the read part). As you can probably tell, i know nothing about reading and writing to files, so please write your answer so a noob can understand. Also the one part of the code that is related to files is a complete stab in the dark and taken from different websites so don't think that i have knowledge on this.

Basically, you create a file object by opening it and then do read or write operation

To read a line from a file

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

To read all lines from file

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

To write a file using python

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

to put it simple, to read a file in python, you need to "open" the file in read mode:

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

The second argument "r" signifies that we open the file to read. After having the file object "f" the content of the file can be accessed by:

content = f.read()

To write a file in python, you need to "open" the file in write mode ("w") or append mode ("a"). If you choose write mode, the old content in the file is lost. If you choose append mode, the new content will be written at the end of the file:

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

To write a string s to that file, we use the write command:

f.write(s)

In your case, it would probably something like:

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

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

I would recommend follow the official documentation as pointed out by cricket_007 : https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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