![](/img/trans.png)
[英]how to read directory (files are n in number) in command prompt using arguments
[英]How to open and read number of files in the same directory and how to define global variable to read files
我想逐个打开并读取同一目录中的文件数。 并对它们执行两个功能。 我面临两个问题:
1我不知道如何为在另一个函数中使用的threshold_file定义一个全局变量。
2此代码正确返回文件名但发生错误
for file in os.listdir("C:/Users/Mariam/PycharmProjects/Group/Copy"):
if file.endswith('b.txt'):
threshold_file = open(file,'r')
readThreshold_file()
position_comparisonFn()
threshold_file = open(file,'r')
FileNotFoundError: [Errno 2] No such file or directory: '1000b.txt'
代码中的文件变量仅存储文件名。 但是在打开文件时,您也应该提供相对路径。
在您的情况下,只需将C:/ Users / Mariam / PycharmProjects / Group / Copy附加到文件变量,您的代码就可以正常工作。
首先 - 将文件变量声明为函数外部的全局,如下所示(不带引号)“global threshold_file”。 然后指定您正在使用全局变量的函数。
第二 - 应该与'Shrey的评论'相同。 详情如下
def func1():
global threshold_file
for file in os.listdir("C:/Users/Mariam/PycharmProjects/Group/Copy"):
if file.endswith('b.txt'):
threshold_file = open("C:/Users/Mariam/PycharmProjects/Group/Copy/"+file,'r')
readThreshold_file()
position_comparisonFn()
def func2():
global threshold_file
...
...
对于你的两个问题:
在函数之外,通常在“导入”部分之后的代码顶部,设置您想要共享的“全局”变量,如下所示:
# Globals
threshold_file = ""
然后,在您要使用该变量的每个函数中,您必须告诉Python您要将该“全局”变量与global
前缀一起使用,如下所示:
def foo():
global threshold_file # Here
for file in os.listdir("C:/Users/Mariam/PycharmProjects/Group/Copy"):
if file.endswith('b.txt'):
threshold_file = open(file,'r')
readThreshold_file()
position_comparisonFn()
注意:您可以使用不带global
前缀的变量,但您只能拥有只读访问权限。 在上面的foo
函数中,您需要它,因为您打算更新/写入该值
将“C:/ Users / Mariam / PycharmProjects / Group / Copy”存储为var,也许作为全局,现在您知道如何
p = r"C:/Users/Mariam/PycharmProjects/Group/Copy" # prefix with 'r' for literal string
并在open()
函数中使用var
...
threshold_file = open(p + r'/' + file,'r') # 'file' is just the filename... need the full path
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.