Python and files (1)

1. Open the file

Open函数:Open(name[. mode[. buffering]])

The file name is a mandatory parameter, and the mode and buffering are optional parameters.

eg:f = Open(r'C:\text\somefile.txt')

value describe
r read mode
w write mode
a Append mode
b Binary mode (processing binary files like sound clips or images)
+

read/write mode

Table 1 Common values ​​of the parameters of the open function mode

0 or false I/O is unbuffered, all read and write operations are directed to the hard disk
1 or true I/O is buffered, using memory instead of hard disk, making programs faster. Only use flush or close to update the data on the hard disk
Greater than 1 The size of the buffer (in bytes)
-1 or how negative Use default buffer size

Table 2 open function buffer parameters

2. Read and write

.write()  .read()

eg:f = open('somefile.txt','+')

 f.write('hello')

 f.read()

 f.read(4) #4 is the number of characters read

 f.close()

3. Tube output

In the UNIX shell, you can use pipes to follow a command to write multiple other commands

eg:$ cat  somefile.txt  |  python somescript.py  |  sort

cat somefile.txt: write the contents of somefile.txt to standard output (sys.stdout)

python somescript.py: run a python script, the script reads from standard input, and writes the result to standard output

sort: read all text from standard input (sys.stdin), sort alphabetically, and write the result to standard output

The pipe command connects the standard output of one command with the standard input of the next command, so somescript.py reads the data written by somefile.txt from its sys.stdin and writes the result to its sys In .stdout, sort can get data from it.

4. Read and write lines

file.readline reads a single line, including newlines

file.readlines reads all lines of a file and returns them as a list

writelines pass it a list of strings, it will write all the strings to the file without word wrapping

Without writeline, use the write method

5. Close the file

Use the close method

Make sure the file is closed, you can use try/finally, and call close in finally

try:

  #write file to your data

finally:

  file.close()

You can also use the with statement. The with statement can open a file and assign it to a variable. The file will be automatically closed after the statement ends.

with open("somefile.txt") as somefile:

  do_something(somefile)

 

 

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325086038&siteId=291194637