How to read txt files in python: first open the file, the code is [f = open('/tmp/test.txt')]; then read, the code is [
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 '/tmp/test.txt', mode 'r' at 0x7fb2255efc00>
2. Reading files ##Steps: Open--Read--Close
>>> f = open('/tmp/test.txt') >>> f.read() 'hello python!\nhello world!\n' >>> f.close()
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
For example, the following is the txt file to be read
After reading, view the read data in the variable window of Enthought Canopy. POS is on the left and Efield is on the right.
Related free learning recommendations:
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!