In the Python programming language, there are many useful operation skills worth mastering in learning and practice to help us use this language to implement various functions. Here we will first take a look at the Python file operations related application skills.
Now we will take txt as an example to briefly introduce Python file operations.
The first step is to establish an association... assume that the following file e: test.txt exists.
- This is line #1
- This is line #2
- This is line #3
- END
- >>> f = file('e:\test.txt', 'r')
The first part of the keyword is the file path and name. Note that \ is required for the path \
The second part is the file mode or permission, which generally has the following three types: "r" (read), "w" (write) and "a" (append ).
Then, you can use
- f_content = infile.read()
- f_content = infile.readlines()
To read the file content.
- >>> f = file('e:\test.txt', 'r')
- >>> ff_content = f.read()
- >>> print f_content
- This is line #1
- This is line #2
- This is line #3
- END
- >>> f.close()
- >>>
- >>> infile = file('e:\test.txt', 'r')
- >>> f = file('e:\test.txt', 'r')
- >>> for f_line in f.readlines():
- print 'Line:', f_line
- Line: This is line #1
- Line: This is line #2
- Line: This is line #3
- Line: END
- >>> f.close()
- >>>
Then write the file
- >>> f=file('e:\test.txt','w')
- >>> f.write('billrice')
- >>> f.write('testtest')
- >>> f.write('entern')
- >>> f.writelines(['billrice','ricerice'])
- >>> f.close()
- >>>
- >>> f=file('e:\test.txt','r')
- >>> content=f.read()
- >>> print content
- billricetesttestenter
- billricericerice
- >>>
In the pythonfile operation, the website is ...in front of f.close(), the C drive has only an empty test.txt, and f. close () serves as the final storage disk.
Delete an object:
- name='e:1.txt'
- os.remove(name)
Compressed file:
- Import OS
- Import zipfile
- Import time
- # Compressing Directories
- Source_dir = r 'f: web'
- # Generate file names by Time
- Target_file = time. strftime ('% Y % m % d % H % M % s') + '.zip'
- MyZipFile = zipfile. ZipFile (target_file, 'w') # compress all files, including subdirectories
- For root, dirs, files in OS. walk (source_dir ):
- For vfileName in files:
- FileName = OS. path. join (root, vfileName)
- MyZipFile. write (fileName, fileName, zipfile. ZIP_DEFLATED)
- # Compression completed
- MyZipFile. close ()
The above is the Python file operation details.