1. Select the folder, right-click, and click New Python file
2. After the name is good, the creation of the file is my life.
3. After the file name is good, you can edit the code
Such as:
Nf=open ("Pi_digits.txt", "W")
Nf.write ("3.14159265358979323846 ...")
4. After the code is edited, you can click the right mouse button and click ' Run to create the file '
5. Create a Python file again, as named read
Edit the code as follows:
With open (' Pi_digits.txt ') as File_object:
Contents=file_object.read ()
Print (contents)
6. After editing the code OK, compile and run the program. You can now see the contents of the file we created
function open ()
To use a file in any way-even if it is just to print its contents-you have to open the file before you can access it. The function open () takes a parameter: the name of the file to open. Python looks for the specified file in the same directory as the currently executing file. In this example, the current run is to read the file. py, so Python looks for the pi_digits.txt in the directory where the file is read. py. The function open () returns an object representing the file. Here, open (' Pi_digits.txt ') returns an object representing the file Pi_digits.txt, and Python stores the object in the variable we will use later.The keyword with is closed after you no longer need to access the file. In this program, notice that we called open (), but did not call Close (); You can also call open () and close () to turn the file on and off, butWhen you do this, the file will not close if there is a bug in the program that causes the close () statement to not execute. This may seem trivial, but failure to properly close the file can result in data loss or damage. If you prematurely tune in the program,with Close (), you will find that you need to use the file when it is closed (inaccessible), which results in more errors. It's not always easy to determine the right time to close a file, but by using the structure shown earlier, you canlet Python decide: you just open the file and use it when you need it, and Python will automatically turn it off at the right time. with the file object representing Pi_digits.txt, we use the method read () (line 2nd of the preceding program) to read the entire contents of the file and store it as a long string in the variable contents. Thus, byBy Printing the value of the contents, you can display the entire contents of the text file:
Create files in Python, read file contents