【问题标题】:IOError: [Errno 2] No such file or directory:'ux_source_2850.txtIOError: [Errno 2] 没有这样的文件或目录:'ux_source_2850.txt
【发布时间】:2013-08-28 22:37:44
【问题描述】:

我正在尝试使用此 python 代码将文件转换为另一种格式,该代码需要三个参数输入文件、输出文件和百分比值。我在 shell 脚本中调用 python 函数,它第一次工作正常,但第二次不工作。错误是“IOError:[Errno 2] 没有这样的文件或目录:'ux_source_2850.txt”。但我很确定这个文件在这个目录中。有人可以帮帮我吗。 另外,我想知道是否有另一种调用python函数的方法,比如编译的c函数,所以我可以与几个参数一起执行该函数。

#!/usr/bin/env python
def convertfile(file1,file2,percentage): 
  with open(file1, "r+") as infile, open(file2, "w+") as outfile:
    outfile.write('lon lat Ve Vn Se Sn Cen Site Ref\n')
    for line in infile.readlines():
      line = line.strip()
      new_line=line + " "+percentage+" "+percentage+" "+'0.05 stat(0,0) test1'+'\n'
      outfile.write(new_line)
file1=raw_input()                                                              
file2=raw_input()                                                              
percentage=raw_input()                                                         
convertfile(file1,file2,percentage)

#!/bin/bash
infile1=ux_source_$j.txt                                                       
outfile1=ux_$j.txt                                                             
percentage1=`sort biggest_z_amp  | tail -1 | awk '{print $1*2e4}'`             
../convertfile.py<<!                                                           
$infile1                                                                       
$outfile1                                                                      
$percentage1                                                                   
!                                                                              
infile2=uy_source_$j.txt                                                       
outfile2=uy_$j.txt                                                             
../convertfile.py<<!                                                           
$infile2                                                                       
$outfile2                                                                      
$percentage1                                                                   
!              

【问题讨论】:

  • "但是我很确定这个文件在这个目录中" 你确定吗?我认为这可能失败的唯一原因是文件确实不存在。

标签: python


【解决方案1】:

您的问题可能出在 shell 脚本上,而不是 Python 脚本上。确保在作为 Python 脚本输入的行中没有尾随空格。

更好的是,使用:

file1 = raw_input().strip()
file2 = raw_input().strip()

【讨论】:

  • 非常感谢。有用。请问这里的“strip”是做什么的?而且我在我的 shell 脚本中找不到任何可能导致这种情况的错误。
  • 在您的 shell 脚本中,以 $infile 开头的行有尾随空格。当 Python 脚本读取该行时,它认为输入文件的名称是"ux_source_2850.txt "(末尾有多个空格),而不仅仅是"ux_source_2850.txt"strip 方法从字符串的开头和结尾删除白色字符。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-26
相关资源
最近更新 更多