【问题标题】:Python: Dynamically add relative path, based on OSPython:动态添加相对路径,基于操作系统
【发布时间】:2013-04-21 14:05:01
【问题描述】:

我用 Python 为我父亲编写了我的第一个程序,将他拥有的大约 1000 个旧 AppleWorks 文件(不再支持 AppleWorks 格式 .cwk)转换为 .docx。澄清一下,该程序实际上并没有转换任何内容,它所做的只是将您指定的文档中的任何文本复制/粘贴到您想要的任何文件类型的另一个文档中。

该程序在我的 Windows 笔记本电脑上运行良好,但在我父亲的 Mac 笔记本电脑上遇到了问题。

Windows 中的文件路径用\ 表示,而在Mac 中它是/。因此,当程序到达copypaste 变量时,如果相应字符串中的斜杠出现错误,它就会停止工作。

有没有办法让 Python 在不使用字符串的情况下根据操作系统将 InputOutput 文件夹动态添加到我的 copypaste 变量中?

如果您可以看到任何其他改进,请随时说出来,我有兴趣将其作为免费软件发布,可能与 tKinter GUI 一起发布,并希望尽可能使用户友好。

就目前而言,该程序确实存在一些问题(将撇号转换为欧米茄符号等)。随意尝试该程序,看看您是否可以改进它。

import os, os.path
import csv
from os import listdir
import sys
import shutil

path, dirs, files = os.walk(os.getcwd() + '/Input').next()

file_count = len(files)
if file_count > 0:
  print "There are " + str(file_count) + " files you have chosen to convert."
else:
  print "Please put some files in the the folder labelled 'Input' to continue."
ext = raw_input("Please type the file extension you wish to convert to, making sure to     preceed your selection with '.' eg. '.doc'")

convert = raw_input("You have chosen to convert " + str(file_count) + " files to the "     + ext + " format. Hit 'Enter' to continue.")
if convert == "":
  print "Converter is now performing selected tasks."
  def main():
    dirList = os.listdir(path)
    for fname in dirList:
      print fname
      # opens files at the document_input directory.
      copy = open(os.getcwd() + "\Input\\" + fname, "r")
      # Make a file called test.docx and stick it in a variable called 'paste'
      paste = open(os.getcwd() + "\Output\\" + fname + ext, "w+")
      # Place the cursor at the beginning of 'copy'
      copy.seek(0)
      # Copy all the text from 'copy' to 'paste'
          shutil.copyfileobj(copy,paste)
          # Close both documents
          copy.close()
          paste.close() 
      if __name__=='__main__':
        main()
    else:
      print "Huh?"
      sys.exit(0)

如果我不清楚或遗漏了一些信息,请告诉我...

【问题讨论】:

    标签: python text operating-system filepath


    【解决方案1】:

    使用os.path.join

    例如,您可以获取Input 子目录的路径

    path = os.path.join(os.getcwd(), 'Input')
    

    【讨论】:

      【解决方案2】:

      os.path.join 是独立于平台的路径加入方式:

      >>> os.path.join(os.getcwd(), 'Input', fname)
      'C:\\Users\\Blender\\Downloads\\Input\\foo.txt'
      

      在 Linux 上:

      >>> os.path.join(os.getcwd(), 'Input', fname)
      '/home/blender/Downloads/Input/foo.txt'
      

      【讨论】:

      • 感谢 Blender,你和 Sapi 都给了我我想要的东西。不幸的是,萨皮比你早了几秒钟,所以我不得不给他打勾。但请接受安慰票。
      • @Sam:没有那个赞,我还是会在桌子底下抽泣 ;-)
      猜你喜欢
      • 2020-05-17
      • 2017-03-25
      • 2019-10-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多