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

Python 在文件夹中的每个文本文件上运行脚本

Python 在文件夹中的每个文本文件上运行脚本,python,input,Python,Input,我希望在一个目录中的所有文本文件上运行我的脚本,但是我遇到了很多麻烦 以下是我目前掌握的代码: data = {} date = ID = values = None infile = "z140327b.txt" outfile = "oz140327b.txt" sample = 1 with open(infile) as datafile, open(outfile, 'w') as f2: for line in datafile: if line.l

我希望在一个目录中的所有文本文件上运行我的脚本,但是我遇到了很多麻烦

以下是我目前掌握的代码:

data = {}

date = ID = values = None


infile = "z140327b.txt"
outfile = "oz140327b.txt"

sample = 1

with open(infile) as datafile, open(outfile, 'w') as f2:
    for line in datafile:
        if line.lstrip().startswith('!'):
            date = line[1:].strip()
        elif line.lstrip().startswith('?'):
            sample = 2
        elif line.lstrip().startswith('@'):
            ID = line[1:].strip()
            data[ID] = {}
            data[ID]['date'] = date
            tedtime = ID[0:2] + ":" + ID[2:]
            str_1 = str(data[ID])
            f2.write(tedtime + ' ' + date + ',' + str(sample))
        elif line.strip():
            if not ID: 
                continue
            try:
                words = line.split()
                value = float(words[-1]) # last word
                unit = words[-2].lstrip('(').rstrip(')')
                item = {'value': value, 'unit': unit}
                key = ' '.join(words[:-2])
                data[ID][key] = item
            except (ValueError) as err:
                print("Could not parse this line:")
                print(line)
                continue
        else: # if 'empty' line
            ca_str = str(data[ID]['Contact Angle']['value'])
            f2.write(',' + ca_str + '\n')
            ID = None
    ca_str2 = str(data[ID]['Contact Angle']['value'])
    f2.write(',' + ca_str2 + '\n')

此时,我正在手动添加文件名(infile)和输出文件名(outfile)。我希望输出文件名与输入文件名相同,前面有一个“o”,如示例代码所示。

您可以使用glob获取目录中的所有文件:

from glob import glob
files=glob('*.txt')
for filename in files:
    with open(filename,'r') as f, open('o'+filename,'w') as f1:
         .... 
         #read from f
         #write to f1
只需在每个文件名上迭代,做您想做的事情,然后将其写入一个新文件。
确保您的脚本是从您所在的目录运行的,或者您需要将路径传递到glob。

如果您想使用文件,请尝试使用“嗖”作为操作的旁白:如果该目录中唯一的文件是目标文本文件,您可以使用
os.listdir()
而不是
glob(*.txt”)
。我喜欢
glob
,但如果您不需要,则无需在脚本中添加新模块(“dependency”这个词对于stdlib模块来说可能太强了)。这个答案没有向OP解释如何从旧文件名生成新文件名。如果你解决了这个问题,它将+1。
import glob
import os.path

def text_files(target_dir):
    """Return (infile, outfile) tuple for all *.txt files in target_dir."""
    text_files = os.path.join(target_dir, '*.txt')
    for fname in glob.glob(text_files):
        outfile = 'o' + os.path.basename(fname)
        outfile = os.path.join(target_dir, outfile)
        yield fname, outfile


# Search for text files in /tmp
for inf, outf in text_files("/tmp"):
    print inf, outf