Home > Backend Development > Python Tutorial > How to read txt file in python

How to read txt file in python

coldplay.xixi
Release: 2020-12-22 16:05:51
Original
10872 people have browsed it

How to read txt files in python: first open the file, the code is [f = open('/tmp/test.txt')]; then read, the code is [

How to read txt file in python

The operating environment of this tutorial: Windows 7 system, python version 3.9. This method is suitable for all brands of computers.

How to read txt files in python:

1. Opening and creating files

>>> f = open('/tmp/test.txt')
>>> f.read()
'hello python!\nhello world!\n'
>>> f
<open file &#39;/tmp/test.txt&#39;, mode &#39;r&#39; at 0x7fb2255efc00>
Copy after login

2. Reading files                                                                                                       ##Steps: Open--Read--Close

>>> f = open(&#39;/tmp/test.txt&#39;)
>>> f.read()
&#39;hello python!\nhello world!\n&#39;
>>> 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 = &#39;array_reflection_2D_TM_vertical_normE_center.txt&#39; # txt文件和当前脚本在同一目录下,所以不用写具体路径
pos = []
Efield = []
with open(filename, &#39;r&#39;) 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()] # 将整行数据分割处理,如果分割符是空格,括号里就不用传入参数,如果是逗号, 则传入‘,&#39;字符。
     pos.append(p_tmp)  # 添加新读取的数据
     Efield.append(E_tmp)
     pass
   pos = np.array(pos) # 将数据从list类型转换为array类型。
   Efield = np.array(Efield)
   pass
Copy after login

For example, the following is the txt file to be read

How to read txt file in pythonAfter reading, view the read data in the variable window of Enthought Canopy. POS is on the left and Efield is on the right.

How to read txt file in python

Related free learning recommendations:

python video tutorial

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