How to read the content of txt file in python

Release: 2019-07-06 08:57:49
Original
18592 people have browsed it

How to read the content of txt file 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

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 a list, and then use the numpy scientific computing package to convert the list data into array format, so that scientific calculations can be performed like MATLAB.

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

For more Python-related technical articles, please visit Python tutorial column for learning!

The above is the detailed content of How to read the content of txt file 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