Home > Backend Development > Python Tutorial > How to read text files in python

How to read text files in python

藏色散人
Release: 2019-10-15 11:45:27
Original
4692 people have browsed it

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()
Copy after login

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
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template