从Python中名为文本文件的事件中分离并处理奇怪的命名文本文件

时间:2013-11-19 04:41:08

标签: import shutil

我是编程和新手的新手。 python,并试图编写一个程序来处理天文数据。我有一个巨大的文件列表,命名如ww_12m_no0021.spc,ww_12m_no0022.spc等。我想将所有奇数编号的文件和偶数编号的文件移动到两个单独的文件夹中。

import shutil
import os


for file in os.listdir("/Users/asifrasha/Desktop/python_test/input"):
    if os.path.splitext(file) [1] == ".spc":
        print file
        shutil.copy(file, os.path.join("/Users/asifrasha/Desktop/python_test/output",file))

实际上是将所有spc文件复制到另一个文件夹。我正在努力解决如何将奇数文件(no0021,no0023 ...)复制到一个单独的文件夹。任何帮助或建议将不胜感激!!!

2 个答案:

答案 0 :(得分:1)

import os
import shutil

# Modify these to your need
odd_dir = "/Users/asifrasha/Desktop/python_test/output/odd"
even_dir = "/Users/asifrasha/Desktop/python_test/output/even"

for filename in os.listdir("/Users/asifrasha/Desktop/python_test/input"):
    basename, extenstion = os.path.splitext(filename)
    if extenstion == ".spc":
        num = basename[-4:]  # Get the numbers (i.e. the last 4 characters)
        num = int(num, 10)   # Convert to int (base 10)
        if num % 2:    # Odd
            dest_dir = odd_dir
        else:          # Even
            dest_dir = even_dir
        dest = os.path.join(dest_dir, filename)
        shutil.copy(filename, dest)

显然你可以稍微简化一下;我只是想尽可能清楚。

答案 1 :(得分:0)

假设您的文件名为ww_12m_no,后跟数字:

if int(os.splitext(file)[0][9:])%2==1:
    #file is oddly numbered, go ahead and copy...

如果名称前半部分的长度发生变化,我会使用正则表达式...我没有测试代码,但这是它的要点。我不确定这个问题属于这里......