Home  >  Article  >  Backend Development  >  How to read text files in python

How to read text files in python

藏色散人
藏色散人Original
2019-10-15 11:45:274648browse

How to read text files in python

How to read text files in python?

Reading files

Steps: Open--Read--Close

>>> f = open('/tmp/test.txt')
>>> f.read()
'hello python!\nhello world!\n'
>>> f.close()

Related recommendations: "Python Tutorial"

Reading data is a necessary step for post-data processing.

.txt is a widely used data file format. Some .csv, .xlsx and other files can be converted to .txt files for reading.

I often use the I/O interface that comes with Python to read the data and store it in the list, and then use the numpy scientific computing package to convert the list data into array format, so that it can be used like MATLAB Perform scientific calculations the same way.

The following is a commonly used code for reading txt files, which can be used in most txt file readings

filename = 'array_reflection_2D_TM_vertical_normE_center.txt' # txt文件和当前脚本在同一目录下,所以不用写具体路径
pos = []
Efield = []
with open(filename, 'r') as file_to_read:
  while True:
    lines = file_to_read.readline() # 整行读取数据
    if not lines:
      break
      pass
     p_tmp, E_tmp = [float(i) for i in lines.split()] # 将整行数据分割处理,如果分割符是空格,括号里就不用传入参数,如果是逗号, 则传入‘,'字符。
     pos.append(p_tmp)  # 添加新读取的数据
     Efield.append(E_tmp)
     pass
   pos = np.array(pos) # 将数据从list类型转换为array类型。
   Efield = np.array(Efield)
   pass

The above is the detailed content of How to read text files in python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn