Yan*_*nis 7 io user-input file input python-3.x
我有一个Python脚本,该脚本打开位于特定目录(工作目录)中的特定文本文件并执行一些操作。
(假设目录中有一个文本文件,那么它将永远不超过一个.txt)
with open('TextFileName.txt', 'r') as f:
for line in f:
# perform some string manipulation and calculations
# write some results to a different text file
with open('results.txt', 'a') as r:
r.write(someResults)
Run Code Online (Sandbox Code Playgroud)
我的问题是,如何让脚本在目录中找到文本(.txt)文件并打开它,而无需显式提供其名称(即,不提供'TextFileName.txt')。因此,运行该脚本不需要打开哪个文本文件的参数。
有办法在Python中实现吗?
您可以os.listdir用来获取当前目录中的文件,并通过扩展名对其进行过滤:
import os
txt_files = [f for f in os.listdir('.') if f.endswith('.txt')]
if len(txt_files) != 1:
raise ValueError('should be only one txt file in the current directory')
filename = txt_files[0]
Run Code Online (Sandbox Code Playgroud)
你也可以使用glob比os
import glob
text_file = glob.glob('*.txt')
# wild card to catch all the files ending with txt and return as list of files
if len(text_file) != 1:
raise ValueError('should be only one txt file in the current directory')
filename = text_file[0]
Run Code Online (Sandbox Code Playgroud)
glob 搜索由设置的当前目录 os.curdir
您可以通过设置更改到工作目录
os.chdir(r'cur_working_directory')