Using Python files to input arrays can use the numpy.loadtxt() function. The specific steps are as follows: Import the NumPy library and open the file. Use the loadtxt() function to read the file, specifying the data delimiter. For example, suppose there are comma-separated data 1,2,3,4,5,6,7,8,9 in my_data.txt, which can be read using the following code: import numpy as np with open('my_data.txt', 'r') as f: data = np.loadtxt(f, delimiter=',')
##How to use Python file input array
In Python, you can use thenumpy.loadtxt() function to read data from a file and convert it into an array.
Steps:
<code class="python">import numpy as np</code>
<code class="python">with open('my_data.txt', 'r') as f: # 这里输入文件路径和读取模式('r')</code>
function to read the file:
<code class="python">data = np.loadtxt(f, delimiter=',')</code>
The parameter specifies the delimiter of the data (default is space).
Example:
Suppose you have a text file namedmy_data.txt that contains the following data (separated by commas ):
<code>1,2,3 4,5,6 7,8,9</code>
<code class="python">import numpy as np with open('my_data.txt', 'r') as f: data = np.loadtxt(f, delimiter=',') print(data)</code>
<code>[[1. 2. 3.] [4. 5. 6.] [7. 8. 9.]]</code>
Note:
parameter.
parameter to specify the type of data (default is float).
function.
The above is the detailed content of How to use file input array in python. For more information, please follow other related articles on the PHP Chinese website!