Python read write file manipulation sample program

  • 2020-04-02 13:15:24
  • OfStack

Example file manipulation


# The input file 
f = open(r'D:Python27pro123.bak') 
# The output file 
fw = open(r'D:Python27pro123e.bak','w')
# Read all text in line 
lines = f.readlines()
num = -1
for line in lines:
    str = '@SES/%i/' %num
    line = line.replace('@SES/1/',str)
    num = num + 1
    # Written to the file 
    fw.writelines(line)
# Close the file handle 
f.close()
fw.close()

Note that the two functions that are commonly used for writing files are write() and writelines()
File. Write (STR): writes the string STR to a file
File. writelines(seq) : writes the entire seq sequence to a file
Both of these functions only write data, not a newline. If a newline is needed, manually add '\n' to the end of STR:

Line breaks are defined differently in each operating system, '\r \n' for Windows, '\n' for Unix/Linux and '\r' for Mac.
In python, the newline character is unified, defined as '\n', when written in text mode, if it is a Windows system, python will automatically convert \n to \r\n, similar to Mac system;
The default read-write operation is to open the file in text mode: f = open(r'd :\Python27\pro\123. Bak ','w')
If opened in binary mode, specify parameter b: f = open(r'd :\Python27\pro\123. Bak ','rb')


Related articles: