Python:基于操作系统动态添加相对路径

Sam*_*Sam 2 python text operating-system filepath

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

该程序在我的Windows笔记本电脑上工作正常,但它遇到了我父亲的Mac笔记本电脑的问题.

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

有没有办法让Python动态添加上InputOutput文件夹,我copypasteOS上的变量,取决于在不使用的字符串?

如果您可以看到任何其他改进,请随意说出来,我有兴趣将其作为免费软件发布,可能使用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)
Run Code Online (Sandbox Code Playgroud)

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

sap*_*api 7

使用 os.path.join

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

path = os.path.join(os.getcwd(), 'Input')
Run Code Online (Sandbox Code Playgroud)