系统相关
首页 > 系统相关> > 文件 – Linux如何区分以读取模式打开文件和实际从中读取数据?

文件 – Linux如何区分以读取模式打开文件和实际从中读取数据?

作者:互联网

我创建了一个简单的文本文件并使用stat检查其时间戳,这里是输出:

stat Output before any python script

papagolf@Sierra ~/My Files/My Programs/Learning/Python % stat prac09_timestamp.txt 
  File: prac09_timestamp.txt
  Size: 10          Blocks: 8          IO Block: 4096   regular file
Device: 802h/2050d  Inode: 2485542     Links: 1
Access: (0600/-rw-------)  Uid: ( 1000/papagolf)   Gid: ( 1001/papagolf)
Access: 2017-09-10 11:10:40.979845492 +0530
Modify: 2017-09-10 11:10:40.979845492 +0530
Change: 2017-09-10 11:10:40.979845492 +0530
 Birth: -

然后我运行了一个python脚本,它只是以读取模式打开文件.我期待时间“访问”标记改变,但它没有.

Python Script and output of stat after running it

papagolf@Sierra ~/My Files/My Programs/Learning/Python % cat python prac09_timestamp.py 
cat: python: No such file or directory
a = open("prac09_timestamp.txt", "r")
a.close()
papagolf@Sierra ~/My Files/My Programs/Learning/Python % python prac09_timestamp.py 
papagolf@Sierra ~/My Files/My Programs/Learning/Python % stat prac09_timestamp.txt 
  File: prac09_timestamp.txt
  Size: 10          Blocks: 8          IO Block: 4096   regular file
Device: 802h/2050d  Inode: 2485542     Links: 1
Access: (0600/-rw-------)  Uid: ( 1000/papagolf)   Gid: ( 1001/papagolf)
Access: 2017-09-10 11:10:40.979845492 +0530
Modify: 2017-09-10 11:10:40.979845492 +0530
Change: 2017-09-10 11:10:40.979845492 +0530
 Birth: -

但是当我更改脚本以实际读取数据时,时间戳会发生变化.你能解释一下吗?

New Python Script and output of stat after running it

papagolf@Sierra ~/My Files/My Programs/Learning/Python % cat prac09_timestamp.py 
a = open("prac09_timestamp.txt", "r")
a.readlines()
a.close()
papagolf@Sierra ~/My Files/My Programs/Learning/Python % python prac09_timestamp.py
papagolf@Sierra ~/My Files/My Programs/Learning/Python % stat prac09_timestamp.txt 
  File: prac09_timestamp.txt
  Size: 10          Blocks: 8          IO Block: 4096   regular file
Device: 802h/2050d  Inode: 2485542     Links: 1
Access: (0600/-rw-------)  Uid: ( 1000/papagolf)   Gid: ( 1001/papagolf)
Access: 2017-09-10 11:13:12.699848321 +0530
Modify: 2017-09-10 11:10:40.979845492 +0530
Change: 2017-09-10 11:10:40.979845492 +0530
 Birth: -

解决方法:

我认为这根本不是一个Python问题.这是系统级别.在该级别打开文件与读取文件完全不同.我不是Linux内部的任何想象力的专家,但这里有一些基本的事实:

>使用open(2)系统调用打开文件.
>使用read(2)系统调用读取文件
> open(2)有一个标志,指示系统在调用read(2)时不更新访问时间.它被称为O_NOATIME
>您可以从中推断出open(2)不会更新访问时间

如果你考虑访问这个词意味着什么是有道理的. open(2)返回一个文件描述符,该描述符随后可用于读取文件.使用粗略的比喻,就像拥有音乐会的全访问通道一样.直到你出现并开始在追逐阶段的群体,你没有访问任何东西.

标签:python,files,timestamps
来源: https://codeday.me/bug/20190816/1665138.html