读取路径>文件作为字符串 - “AttributeError: 'str'对象没有'open'属性”为什么?

2 投票
1 回答
20297 浏览
提问于 2025-04-17 20:27

在下面的代码中,它把 out_file 当作一个字符串来处理,我搞不清楚为什么。如果我不把它当作字符串,系统就会提示文件位置不正确。看起来 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'

1 个回答

0

这完全是错误的:

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

out_file.close()

正确使用 openreadwritereadlines 的方法是:

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())
  1. 如果你使用 with 来打开文件,就不需要再调用 close() 了(这就是 with 的意义所在:它会自动帮你关闭文件)。

  2. 因为你想从一个文件中读取所有内容并写入另一个文件,所以应该使用 read() 而不是 readlines():也就是说,获取所有内容,然后写入所有内容。

如果你真的想使用 readlines(),那么像下面这样做会更好:

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

撰写回答