from os.path import baspath, expanduser
filepath = abspath(expanduser("~/") + '/Downloads/DeletingDocs.txt')
print('Opening file', filepath)
with open(filepath, 'r') as fh:
print(fh.read())
请注意 OSX 文件处理,IO 会根据文件类型有所不同。例如,.txt
在 Windows 下将被视为“纯文本文件”的文件实际上是 OSX 下的压缩数据流,因为 OSX 试图对存储空间“智能”。
除非你知道这件事,否则这会彻底毁掉你的一天(去过那里,头疼..继续前进)
例如,当在 OSX 中双击.txt
文件时,通常会弹出文本编辑器,它的作用是调用 aos.open()
而不是在较低级别访问它,这让 OSX 中间层可以这样做disk-area|decompression pipe|file-handle -> Texteditor
,但是如果您在 a 上访问文件对象较低级别您最终将打开存储文件的磁盘区域,如果您打印数据,您将得到垃圾,因为它不是您期望的数据。
所以尝试使用:
import os
fd = os.open( "foo.txt", os.O_RDONLY )
print(os.read(fd, 1024))
os.close( fd )
并摆弄旗帜。老实说,我不记得这两个中的哪一个按原样从磁盘(open()
或os.open()
)打开文件,但其中一个使您的数据看起来像垃圾,有时您只是获得指向解压缩管道的指针(给您 4 个字节的数据即使文本文件是巨大的)。
如果它正在跟踪/捕获您想要的文件的更新
from time import ctime
from os.path import getmtime, expanduser, abspath
from os import walk
for root, dirs, files in walk(expanduser('~/')):
for fname in files:
modtime = ctime(getmtime(abspath(root + '/' + fname)))
print('File',fname,'was last modified at',modtime)
如果时间与您上次检查的时间不同,那就用它做一些很酷的事情。例如,您可以使用以下 Python 库:
还有更多,因此不要将打开外部应用程序作为您的第一个修复程序,而是尝试通过 Python 打开它们并根据您的喜好进行修改,并且只能作为最后的手段(即使那样)通过 Popen 打开外部应用程序。
但既然你要求它(有点……呃),这里有一个Popen 方法:
from subprocess import Popen, PIPE, STDOUT
from os.path import abspath, expanduser
from time import sleep
run = Popen('open -t ' + abspath(expanduser('~/') + '/example.txt'), shell=True, stdout=PIPE, stdin=PIPE, stderr=STDOUT)
##== Here's an example where you could interact with the process:
##== run.stdin.write('Hey you!\n')
##== run.stdin.flush()
while run.poll() == None:
sleep(1)
过度解释你的工作:
这将在每次更改时打印文件内容。
with open('test.txt', 'r') as fh:
import time
while 1:
new_data = fh.read()
if len(new_data) > 0:
fh.seek(0)
print(fh.read())
time.sleep(5)
工作原理:
常规文件打开器with open() as fh
将打开文件并将其作为句柄放置在 中fh
,一旦您.read()
不带任何参数调用,它将获取文件的全部内容。这反过来不会关闭文件,它只是将“读取”指针放在文件的后面(为了方便起见,我们说在位置 50)。
所以现在你的指针位于文件中的第 50 个字符处,最后。无论您在文件中的何处写入内容,都会将更多数据放入其中,因此下一个.read()
将从位置 50+ 获取数据,使该位置.read()
不为空,因此我们通过发出将“读取”指针放回位置 0 .seek(0)
,然后打印所有数据。
将其与os.path.getmtime()
任何反向更改或 1:1 比例更改(替换字符拼写错误等)相结合。