Python 读取路径>;文件格式为字符串-";属性错误:';str';对象没有属性';打开'&引用;为什么?

Python 读取路径>;文件格式为字符串-";属性错误:';str';对象没有属性';打开'&引用;为什么?,python,python-2.7,Python,Python 2.7,在下面的代码中,它将out_文件作为字符串读取,我似乎不知道为什么。如果我不将其视为字符串,那么它会说文件位置不正确。它读src_dir显然很好。提前感谢您的帮助。我对python非常陌生,并且自学 import os import os.path import shutil '''This is supposed to read through all the text files in a folder and copy the text inside to a master file.'

在下面的代码中,它将out_文件作为字符串读取,我似乎不知道为什么。如果我不将其视为字符串,那么它会说文件位置不正确。它读src_dir显然很好。提前感谢您的帮助。我对python非常陌生,并且自学

import os
import os.path
import shutil

'''This is supposed to read through all the text files in a folder and
copy the text inside to a master file.'''

#   This gets the source and target directories for reading writing the
#   files respectively

src_dir = r'E:\filepath\text_files'
out_file = r'E:\filepath\master.txt'
files = (os.listdir(src_dir))
def valid_path(dir_path, filename):
    full_path = os.path.join(dir_path, filename)
    return os.path.isfile(full_path)
file_list = [os.path.join(src_dir, f) for f in files if valid_path(src_dir, f)]    


#   This should open the directory and make a string of all the files
#   listed in the directory. I need it to open them one by one, write to the
#   master file and close it when completely finished.


open(out_file, 'a+')
with out_file.open() as outfile:
    for element in file_list:
        open(element)
        outfile.append(element.readlines())

out_file.close()

print 'Finished'
这是完全错误的:

open(out_file, 'a+')
with out_file.open() as outfile:
    for element in file_list:
        open(element)
        outfile.append(element.readlines())

out_file.close()
打开
读取
写入
读取行
的正确用法是:

f = open(path_to_file, ...)
f.write(data)
data = f.read()
lines = f.readlines()
f.close()
[以上不是有效的或有效的脚本,只是如何调用每个方法的示例]

因此,要在特定用例中帮助您:

with open(out_file, 'a+') as outfile:
    for element in file_list:
        with open(element) as infile:
            outfile.write(infile.read())
  • 如果将
    关闭一起使用,则不需要
    close()
    (即
    一起使用的全部要点:它为您关闭)

  • 由于您想从一个文件中读取所有内容并写入另一个文件,请使用
    read()
    而不是
    readlines()
    :即获取全部,然后写入全部

  • 如果您真的想使用
    readlines()
    ,那么这样做会更好:

    outfile.write(''.join(infile.readlines())
    

    python站点提供了一些很好的python参考资料。。。包括如何打开文件……值得注意的是,使用
    open
    read
    等示例并不构成有用或有意义的程序。它们的目的是演示哪些是函数,哪些是方法,以及应该调用这些方法的对象。谢谢!这可能会解决我收到的错误消息。这就是问题所在。再次感谢你回答我的问题。