使用其他文件创建和写入文件

2024-05-13 20:11:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我是Python新手,我正在尝试自动化我的一些工作

我需要创建一个与对应的.DS2(口述文件)同名的.wst文件(口述数据文件),然后用数据输入(作者代码、作业类型)填充.wst文件

也许我需要生成一个txt文件,然后将扩展名改为.wst?我不确定

当我运行以下程序时,没有创建任何内容,有人能提供任何建议吗

import os

print('Dictation Zipper 1.0\n')

print('**Warning** What you set in the following fields will apply to ALL dictations in the current folder, please make any manual adjustments after running the tool.\n')

get_directory = input('Enter the file path where the dictations are stored, please use a NEW folder outwith the Share...\n')

author_id = input('Enter the four digit author id...\n')

jobtype_id = input('Enter the job type...\n')

for f in os.listdir():
    file_name, file_ext = os.path.splitext(f) #splitting file name and extension
    wst_file = open(file_name + ".wst", "w+") #creating a wst file 
    wst_file.write("[JobParameters]\nAuthorId=" + author_id + "\nJobtypeId=" + jobtype_id +"\nPriority=NORMAL\nKeyfield=\nUserfield1=\nUserfield2=\nUserfield3=\nUserfield4=\nNotes=\n")
    wst_file.close() #closing wst file

Tags: 文件thenameinidinputosfolder
1条回答
网友
1楼 · 发布于 2024-05-13 20:11:47

您需要将目录名作为os.listdir()的参数。打开文件时,需要在文件名前面加上目录名

for f in os.listdir(get_directory):
    file_name, file_ext = os.path.splitext(f) #splitting file name and extension
    path = os.path.join(get_directory, file_name + ".wst")
    wst_file = open(path, "w+") #creating a wst file 
    wst_file.write("[JobParameters]\nAuthorId=" + author_id + "\nJobtypeId=" + jobtype_id +"\nPriority=NORMAL\nKeyfield=\nUserfield1=\nUserfield2=\nUserfield3=\nUserfield4=\nNotes=\n")
    wst_file.close() #closing wst file

相关问题 更多 >