Python 获取文件第一个字符串的四种方法
Python 获取文件第一个字符串的四种方法
本文介绍了四种使用Python获取文件第一个字符串的方法,并提供了代码示例。
方法一:使用Python内置的文件操作函数
with open('file.txt', 'r') as f:
first_line = f.readline().strip()
方法二:使用pandas库
import pandas as pd
df = pd.read_csv('file.txt', sep=' ', header=None, nrows=1)
first_line = df.values[0][0]
方法三:使用numpy库
import numpy as np
with open('file.txt', 'r') as f:
first_line = np.genfromtxt(f, delimiter=' ', dtype=str, max_rows=1)[0]
方法四:使用numpy和pandas库的结合
import numpy as np
import pandas as pd
df = pd.read_csv('file.txt', sep=' ', header=None, nrows=1)
first_line = np.array(df)[0,0]
以上方法都可以读取文件中的第一个字符串,选择适合自己的方法即可。
原文地址: https://www.cveoy.top/t/topic/okQp 著作权归作者所有。请勿转载和采集!