my_list = [i**2 for i in range(1,11)]
# Generates a list of squares of the numbers 1 - 10
f = open("output.txt", "w") ##Open output.txt in w mode
for item in my_list:
f.write(str(item) + "\n")
f.close()
###You can open files in write-only mode ("w"), read-only mode ("r"), read and write mode ("r+"), and append mode ("a", which adds any new data you write to the file to the end of the file).
read
除了像上面说的,可以打开一个文件,往里面写入需要的内容,还可以读取文件,读取文件的命令:
print f.read()
my_file = open ("output.txt","r")
print my_file.read ()
my_file.close()