Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.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_Loops_Text_Import - Fatal编程技术网

在目录中循环,使用Python按时间顺序导入和处理文本文件

在目录中循环,使用Python按时间顺序导入和处理文本文件,python,loops,text,import,Python,Loops,Text,Import,希望我能在python代码方面得到帮助,目前我必须在每次运行代码时手动更改工作目录,该代码按时间顺序循环遍历所有.txt文件,因为它们的编号为1_Ix_100.txt,2_Ix_99.txt等,直到201_Ix_u-100.txt。所有文本文件都在同一目录中,即C:/test/Ig=*/340_-TXT。更改的是带星号的文件夹,从340到1020,增量为40,即C:/test/Ig=340/340_-TXT,C:/test/Ig=380/340_-TXT等,直到C:/test/Ig=1020/3

希望我能在python代码方面得到帮助,目前我必须在每次运行代码时手动更改工作目录,该代码按时间顺序循环遍历所有.txt文件,因为它们的编号为1_Ix_100.txt2_Ix_99.txt等,直到201_Ix_u-100.txt。所有文本文件都在同一目录中,即C:/test/Ig=*/340_-TXT。更改的是带星号的文件夹,从340到1020,增量为40,即C:/test/Ig=340/340_-TXT,C:/test/Ig=380/340_-TXT等,直到C:/test/Ig=1020/340_-TXT

我正在寻找一种自动化此过程的方法,以便代码在不同的/Ig=*/文件夹中循环,处理文本文件并将结果保存为/Ig中的csv文件=/


我真的希望我的措辞有意义,我感谢任何帮助,谢谢你编辑:Gabriel提到我的范围有点不合适。检查第二个代码blurb以进行修改

我首先将脚本放入一个函数中,该函数的参数之一是
路径
。细节由您决定,这段代码只是详细说明如何循环遍历文件名

for root, _, files in os.walk('C:/test/'):
    for f in files:
        os.chdir(os.path.join(root, f))
        #You now have the paths you need to open, close, etc. 
现在,如果
'C:/test/'
中还有其他垃圾文件,则可以使用基于范围的循环:

min_file_num = 340
max_file_num = 1020
for dir_num in range(min_file_num, max_file_num+1, 40):
   path = 'C:/test/Ig=' + str(dir_num) + '/'
   for root, _, files in os.walk(path):
       for f in files:
        os.chdir(os.path.join(root, f))
        #You now have the paths you need to open, close, etc. 

使用一个简单的循环和一些字符串操作,您可以创建所需路径的列表,然后对它们进行迭代

Ig_txts = []
i=340
while i <= 1020:
    Ig_txts.append( 'Ig='+str(i) )
    i += 40

for Ig_txt in Ig_txts:
    path = 'C:/test/'+Ig_txt+'/340_TXT'
    out_file = 'C:/test/'+Ig_txt+'/Grey_Zone.csv'

    os.chdir(path)
    ...
    ...
Ig_txts=[]
i=340

虽然我只是提醒一下,for循环不会在这里生成最后一个值
dir\u num=1020
。您可以对范围(340、1021、40)中的dir\u num执行
,它将执行。范围上升到上限,但不包括上限。如果答案有帮助,请接受其中一个
Ig_txts = []
i=340
while i <= 1020:
    Ig_txts.append( 'Ig='+str(i) )
    i += 40

for Ig_txt in Ig_txts:
    path = 'C:/test/'+Ig_txt+'/340_TXT'
    out_file = 'C:/test/'+Ig_txt+'/Grey_Zone.csv'

    os.chdir(path)
    ...
    ...