Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
114 views
in Technique[技术] by (71.8m points)

How to create and use a text file in Python?

I need to create a text file in Python to store certain data from a game. I do not want to use numpy, or any external libraries if at all possible.

I need to put some numerical data. Do text files require string data? Also does the data come out of the file as a string?

I know how to create and open a text file, and how to convert string to integer and vice versa, as well as handle CSV file data. I do not know how to handle a text file.

Any ideas on what to do?

question from:https://stackoverflow.com/questions/66061714/how-to-create-and-use-a-text-file-in-python

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

To create a file:

file = open("textfile.txt","w+")

This will create a file if it doesn't exist in the directory.

To write inside it:

file.write("This is the content of the file.")

And then you'll have to close the instance with

file.close()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...