截断文件的分组

我有以下代码:


# function to truncate files

def truncate(path):

    file_to_truncate = open(path, "w")

    file_to_truncate.truncate()

    file_to_truncate.close()



# truncate all relevant files so they are empty and new results are not written underneath another set of results

truncate(r'outputA.csv')

truncate(r'\outputB.csv')

truncate(r'outputC.csv')

truncate(r'outputD.csv')

truncate(r'outputE.csv')

truncate(r'MoutputA.csv')

truncate(r'MoutputB.csv')

truncate(r'MoutputC.csv')

truncate(r'MoutputD.csv')

truncate(r"Full Results.csv")

truncate(r'results.csv')

是否可以缩短此代码,即截断目录中的所有文件。


潇潇雨雨
浏览 79回答 1
1回答

精慕HU

您可以使用os.listdir获取特定目录中的所有文件。然后遍历文件列表并对它们调用你的函数:for file_name in os.listdir():     truncate(file_name)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python