Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/342.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何将文件列表传递给函数,并通过对文件所做的更改获取相同的列表?_Python_List_Function - Fatal编程技术网

Python 如何将文件列表传递给函数,并通过对文件所做的更改获取相同的列表?

Python 如何将文件列表传递给函数,并通过对文件所做的更改获取相同的列表?,python,list,function,Python,List,Function,如何向函数发送文件列表,将regex应用于列表中每个文件中的行并返回新列表?我可以将更改写入新文件,但不知道如何替换列表中的文件并将其发送回。这是我的密码: def apply_regex(myList = [], *args): for index, item in enumerate(myList): file = open(myList[index], 'r') out_file = open(myList[index] + ".regex", "w")

如何向函数发送文件列表,将regex应用于列表中每个文件中的行并返回新列表?我可以将更改写入新文件,但不知道如何替换列表中的文件并将其发送回。这是我的密码:

def apply_regex(myList = [], *args):
   for index, item in enumerate(myList):
      file = open(myList[index], 'r')
      out_file = open(myList[index] + ".regex", "w")
      for line in file:
         line = re.sub('some_regex',r'some_thing_to_sub', line)
         out_file.write(line)
函数调用:

listFile=['file1', 'file2', 'file3']
apply_regex(listFile)

#take some action on listFile based on the new values#

但是我不能从函数中传递新值!我知道我必须写入def apply_regex中的文件,但需要帮助才能写入,然后将其传回。

如果您确实想替换原始列表中的项目:

def apply_regex(myList = [], *args):

   for index, item in enumerate(myList):
      file = open(myList[index], 'r')
      out_file = open(myList[index] + ".regex", "w")
      myList [index] += ".regex"
      for line in file:
         line = re.sub('some_regex',r'some_thing_to_sub', line)
         out_file.write(line)
      out_file.close ()   # Flush buffer

比你还要多,雅克。这正是我想要的。您可以通过在
apply\u regex()
函数的末尾添加一个
return myList
来获得相同的列表。顺便说一句,你可能不应该给myList一个默认值,尤其是像列表这样的可变值。