如何在python中的Mac OSX 10.8.2上打开文件 [英] How to open a file on mac OSX 10.8.2 in python

查看:91
本文介绍了如何在python中的Mac OSX 10.8.2上打开文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在eclipse上编写python代码,并希望打开下载"文件夹中存在的文件.我正在使用MAC OSX 10.8.2.我尝试了f=os.path.expanduser("~/Downloads/DeletingDocs.txt") 以及

I am writing a python code on eclipse and want to open a file that is present in Downloads folder. I am using MAC OSX 10.8.2. I tried with f=os.path.expanduser("~/Downloads/DeletingDocs.txt") and also with

ss=subprocess.Popen("~/Downloads/DeletingDocs.txt",shell=True)
ss.communicate()

我基本上想在子进程中打开一个文件,以侦听打开的文件中的更改.但是,无论哪种情况,该文件都无法打开.

I basically want to open a file in subprocess, to listen to the changes in the opened file.But, the file is not opening in either case.

推荐答案

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有所不同. 例如,在Windows下被视为纯文本文件"的.txt文件实际上是OSX下的压缩数据流,因为OSX试图精简"存储空间.

Take note of OSX file-handling tho, the IO is a bit different depending on the filetype. For instance, a .txt file which under Windows would be considered a "plain text-file" is actually a compressed data-stream under OSX because OSX tries to be "smart" about the storage space.

除非您对此有所了解,否则这可能会彻底毁掉您的一天(在那里,头疼……继续前进)

This can literately ruin your day unless you know about it (been there, had the headache.. moved on)

例如,在OSX中双击.txt文件时,通常会弹出文本编辑器,它的作用是调用os.open()而不是在较低的级别上访问它,这使OSX中间层可以执行disk-area|decompression pipe|file-handle -> Texteditor,但是如果您在较低级别访问文件对象,则最终将打开存储文件的磁盘区域,并且如果您打印数据,则将得到垃圾,因为它不是您期望的数据.

When double-clicking on a .txt file in OSX for instance normally the text-editor pops up and what it does is call for a os.open() instead of accessing it on a lower level which lets OSX middle layers do disk-area|decompression pipe|file-handle -> Texteditor but if you access the file-object on a lower level you'll end up opening the disk-area where the file is stored and if you print the data you'll get garbage because it's not the data you'd expect.

因此请尝试使用:

import os
fd = os.open( "foo.txt", os.O_RDONLY )
print(os.read(fd, 1024))
os.close( fd )

然后随意摆弄标志. 老实说,我不记得这两个从磁盘中按原样打开文件(open()os.open()),但是其中一个使您的数据看起来像垃圾,有时您只是获得了指向解压管道的指针(给出了您甚至需要4个字节的数据,即使文本文件是hughe).

And fiddle around with the flags. I honestly can't remember which of the two opens the file as-is from disk (open() or os.open()) but one of them makes your data look like garbage and sometimes you just get the pointer to the decompression pipe (giving you like 4 bytes of data even tho the text-file is hughe).

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库可以使用:

And if the time differs from your last check, well then do something cool with it. For instance, you have these libraries for Python to work with:

  • .csv
  • .pdf
  • .odf
  • .xlsx

还有很多,因此,除了首先打开外部应用程序外,不要尝试通过Python打开它们,然后根据自己的喜好进行修改,并且只有在万不得已的情况下,才可以通过Popen打开外部应用程序.

And MANY more, so instead of opening an external application as your first fix, try opening them via Python and modify to your liking instead, and only as a last resort (if even then) open external applications via Popen.

但是由于您请求了它(有点... erm),所以这是一种 Popen方法:

But since you requested it (sort of... erm), here's a Popen approach:

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)

过度解释您的工作:

这将在每次更改文件时打印文件内容.

Over-explaining your job:

This will print a files contents every time it's changed.

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处.)

How it works: The regular file opener with open() as fh will open up the file and place it as a handle in fh, once you call .read() without any parameters it will fetch the entire contents of the file. This in turn doesn't close the file, it simply places the "reading" pointer at the back of the file (lets say at position 50 for convenience).

因此,现在您的指针末尾位于文件中的字符50. 无论您在文件中的任何位置写入内容,都会在其中写入更多数据,因此下一个.read()将从位置50+获取数据,从而使.read()不为空,因此我们通过发出命令将读取"指针放回位置0 .seek(0),然后我们打印所有数据.

So now your pointer is at character 50 in your file, at the end. Wherever you write something in your file, that will put more data into it so the next .read() will fetch data from position 50+ making the .read() not empty, so we place the "reading" pointer back to position 0 by issuing .seek(0) and then we print all the data.

将其与os.path.getmtime() 组合在一起以细化任何反向更改或1:1比例更改(替换字符拼写错误等).

Combine that with os.path.getmtime() to fine any reversed changes or 1:1 ratio changes (replacing a character mis-spelling etc).

这篇关于如何在python中的Mac OSX 10.8.2上打开文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆