python file operations (with open) - read lines, write operations

1. Basic grammar

1. Open the file

Only one common method is introduced here, but there are many         ways to open files . Just master the one that suits you best. It is recommended to use this method because there is no need to close. Read the specific reasons below and you will understand after seeing the example . There are many modes for opening files, 'r': reading, 'w': writing, etc., which will not be introduced in detail here.

#采用只读('r')模式,打开当前目录下/path/to/file这个文件(f通俗的可以认为是file文件的小名)
with open( '/path/to/file', 'r' ) as f:
    #将file文件的全部内容直接输出
    print(f.read())

2. How to read the file content (2. There are specific use cases in the examples)

       Personally, I think the most commonly used one is the one marked in red. I will only introduce f.readlines() later . If you want to know about other reading methods, you can go to other people's blogs to see if there are any more complete ones.

  • f.read(): Read the entire file content
  • f.read(size): Read size bytes of content each time
  • f.readline(): Read the contents of one line at a time
  • f.readlines() : Read the entire content, but the result is a list, and each line of content is an element.

2. Example

All the following files are in the same directory . If they are not in the same directory, the path must be written clearly. I use pycharm.

1. Code and required txt files

1) txt file (this file is some random mess I typed)

w100000000500678
w100000001357041
w100000001357041

 2) python runs code (operates files)

#采用只读模式(默认模式),打开当前目录下txt文件(f可以认为是txt的小名)
with open(file="txt") as f:
    #读取文件中全部内容
    lines = f.readlines()
    list = []
    #读取文件中的每一行
    for line in lines:
        #对每一行的内容进行一些字符串操作(包括去除字符串左右两边换行符和'w',和空格)。
        s = line.strip('w').strip('\n').strip()
        #将修改后的每一行加入到列表中
        list.append(int(s))
    #输出list观察是否符合预期
    print(list)
#采用写模式打开result文件,file_handle是result的小名
file_handle = open('result', mode='w')
#将list写入file_handle中(但是写入必须是str,否则报错),也就是result文件
file_handle.write(str(list))
#关闭文件!!直接f = open()需要手动f.close();with open() as f 则不用手动f.close()
file_handle.close()

3) result file (empty at first, only the results after the operation are given here)

Guess you like

Origin blog.csdn.net/weixin_45440484/article/details/128566318
Recommended