打开文件后f.readlines()返回的是一个包含每一行的列表,因此我们可以如下操作(也可以从任意行开始读取):
with open('file_name', 'r') as f:
lines = f.readlines()[1:] # skip the first line.
for line in lines:
print(line)
- 使用next函数跳过第一行读取文件
with open('file_name', 'r') as f:
next(f) # skip the first line.
for line in f.readlines():
print(line)
使用第三方库itertools的islice函数,这个函数根据其第二个参数从任意行开始读取,这里传入1是因为python下标从0开始
from itertools import islice
with open('file_name', 'r') as f:
for line in islice(f, 1, None):
print(line)
Python:对已有内容的TXT文件追加读写
覆盖写入方式:
with open("test.txt", "w") as file:
for i in range(10):
file.write(str(i) + "n")
第二种追加方式:
with open("test.txt", "a") as file:
for i in range(90, 100):
file.write(str(i) + "n")
附:读写txt各参数代表的具体含义
Python判断文件是否存在
入参的路径可以是文件路径也可以是文件夹路径,所以可以用于判断文件以及文件夹是否存在
import os
os.path.exists('xxx/xxx/filename') # True/False
如果path路径存在且不是文件
import pathlib
path = pathlib.Path('/usr/local/file')
path.exist() # True/False 判断路径是否存在
path.is_file # 判断对应路径是否是文件
判断文件读写属性
这里来判断文件读写属性用到的就是os模块里的access方法,格式为:
os.access(path,mode)
path为文件路径,mode为需要判断的属性,主要分为以下四种:
os.F_OK: 判断文件是否存在
os.R_OK: 判断文件是否可读
os.W_OK: 判断文件是否可以写入
os.X_OK: 判断文件是否有执行权限
import os
if not os.access('/usr/local/script/run.sh',os.X_OK):
print "file has no permission to execute!"



