变量文件名未被视为文件,无法打开

时间:2013-12-11 22:27:13

标签: python file-io

这是我使用Python的第三天,我确信很容易被忽视。

我正在尝试索引到html文件名列表,将索引的html文件名设置为var,然后尝试打开该文件。计划是遍历文件名列表。

不幸的是,var不是作为文件读取的,而是作为名称读取。

我认为这是一个容易回答的问题,但我只是找不到它。

那么,我做错了什么?任何帮助将受到高度赞赏。

这是我的代码:

file_list = []
   for root, dirs, files in os.walk(r'C:\Aptana\Beautiful'):
     for file in files:
       if file.endswith('.html'):
          file_list.append(file)
input_file = file_list[0]
orig_file = open(input_file, 'w')

我知道我错过了一些简单的东西,但是它让我疯了!

更新

file_list = []
for root, dirs, files in os.walk(r'C:\Aptana\Beautiful'):
 for file in files:
   if file.endswith('.html'):
      file_list.append(os.path.join(root,file))
     input_file = file_list[0]
     orig_file = open(input_file, 'w')
     soup = BeautifulSoup(orig_file)
     title = soup.find('title')      
     main_txt = soup.findAll(id='main')[0]
     toc_txt = soup.findAll(class_ ='toc-indentation')[0]

然后崩溃:

Traceback (most recent call last):
  File "C:\Aptana\beautiful\B-1.py", line 47, in <module>
   soup = BeautifulSoup(orig_file)
 File "C:\Python33\lib\site-packages\bs4\__init__.py", line 161, in __init__
   markup = markup.read()
 io.UnsupportedOperation: not readable

谢谢adsmith!如果您有任何其他问题,请告诉我。

orig_file正在打印为:     &lt; _io.TextIOWrapper name ='C:\ Aptana \ Beautiful mode ='r'\ Administration + Guide.html'coding ='cp1252'&gt;

2 个答案:

答案 0 :(得分:1)

在我看来,您当前的工作目录与您走的目录不在同一个目录中。试着这样做:

file_list = []
   for root, dirs, files in os.walk(r'C:\Aptana\Beautiful'):
     for file in files:
       if file.endswith('.html'):
          file_list.append(os.path.join(root,file))
input_file = file_list[0]
orig_file = open(input_file, 'w')

我强烈建议您使用“with”contextlib,而不是使用orig_file = open(file)orig_file.close()。而是实现如下:

#walk through your directory as you're doing already
input_file = file_list[0] #you know this is only for the first file, right?
with open(input_file,'w') as orig_file:
  #do stuff to the file
#once you're out of the block, the file automagically closes, which catches
#all kinds of accidental breaks in cases of error or exception.

看起来您的问题是您使用“write”标志而不是“read”标志打开文件。我实际上并不知道BeautifulSoup的作用,但是快速谷歌使它看起来像一个屏幕解析器。将orig_file打开为'r'而不是'w'。

orig_file = open(input_file,'r') #your way
#or the better way ;)
with open(input_file,'r') as orig_file:
  #do stuff to it in the block

无论如何,这更好,因为打开文件'w'会使文件空白:)

答案 1 :(得分:0)

我相信在这里可以找到类似的问题:How to read file attributes in directory?

答案可能包含您正在寻找的信息(使用os.stat或os.path提供文件的实际路径。)