Examples of read and write operations Python study notes analysis of documents

This article describes the Python learning to read and write files of notes, with examples in the form of a detailed analysis of Python common file reading and writing skills and achieve relevant considerations, need friends can refer to the following
reading this example to tell about Python file write operation. Share to you for your reference, as follows:

Reading and Writing Files

Read the file

f = open('my_path/my_file.txt', 'r') # open方法会返回文件对象
file_data = f.read() # 通过read方法获取数据
f.close() # 关闭该文件

First, open the file using the built-in function open. You need the file path string. open function returns a file object, it is a Python object, and the object file by Python itself interaction. In this example, we assign this object to the variable f.
You can specify an optional parameter in the open function. One of the parameters is used to open the file mode. In this example, we use the r, i.e., read-only mode. This is actually the default value of the mode parameter.
Use read access to the contents of the file object. The read method will accept text contained in the file and put the string. In this example, we assign the method returns to the string variable file_data.
When we finished with the file, use the close method of the file release system resources occupied.
Write to file

f = open('my_path/my_file.txt', 'w')
f.write("Hello there!")
f.close()

Open the file in write ( 'w') mode. If the file does not exist, Python will you create a file. If you open an existing file in write mode, all types of content before the file is deleted. If you plan to add content to existing files, but does not delete its contents, you can use the additional ( 'a') mode, rather than writing mode.
Adding text to a file using the write method.
After the operation, close the file.
with syntax that will automatically close the file after you have finished using the file

with open('my_path/my_file.txt', 'r') as f:
file_data = f.read()

The with keyword allows you to open files, perform actions on file and indent your code (in this example, read from a file) automatically closes the file after execution. Now, we do not need to call f.close () up!
Only in this indented block access to the file object f.
In the previous code, f.read () call does not pass parameters. It automatically into all of the remaining contents of the file read from the current position, i.e., the entire file. If you pass an integer parameter to .read (), it will read the content length is so much character, the output of all content, and the 'window' to remain in the position ready to continue reading.

with open(camelot.txt) as song:
  print(song.read(2))
  print(song.read(8))
  print(song.read())

Output:

We
're the
knights of the round table
We dance whenever we’re able

Reads the next line of the file method: f.readlines ()

Python uses the syntax of each line for line in file content iterate file. Can I use this syntax to create a list of rows in the list. Because each line still contain line breaks, so I use .strip () delete the line breaks.

camelot_lines = []
with open("camelot.txt") as f:
  for line in f:
    camelot_lines.append(line.strip())
print(camelot_lines) # ["We're the knights of the round table", "We dance whenever we're able"]

Related exercises: You will create a cast list that lists the TV series "Monty Python's Flying Circus troupe," the actor. Create_cast_list write a function called, the function will accept a file name as input and returns a list of names of actors. It will run file flying_circus_cast.txt. Each line of the file contains the names of actors, commas, and some (messy) information about the program roles. You only need to recall names and added to the list. You can use .split () method of processing each line.

solution:

def create_cast_list(filename):
  cast_list = []
  #use with to open the file filename
  #use the for loop syntax to process each line
  #and add the actor name to cast_list
  with open(filename) as f:
  # use the for loop syntax to process each line    
  # and add the actor name to cast_list
    for line in f:
      line_data = line.split(',')
      cast_list.append(line_data[0])
  return cast_list
cast_list = create_cast_list('./txts/flying_circus_cast.txt')
for actor in cast_list:
  print(actor)

We recommend the python learning sites to see how seniors are learning! From basic python script, reptiles, django, data mining, programming techniques, as well as to combat zero-based sorting data items, given to every love learning python small partner! Python veteran day have to explain the timing of technology, to share some of the ways to learn and need to pay attention to small details, click on Join us python learner gathering

Published 51 original articles · won praise 122 · views 80000 +

Guess you like

Origin blog.csdn.net/haoxun03/article/details/104348928