Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.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_File_Python 2.7 - Fatal编程技术网

在python中编辑文件中的文本

在python中编辑文件中的文本,python,file,python-2.7,Python,File,Python 2.7,我是python新手,正在使用python获取输入并编辑文件。我要编辑的值是“web iphone”,其中包含我从输入中获得的文本 迄今为止的代码: web = raw_input("Enter value") 文件:test.py local { value web-iphone } 编辑:现在你的问题更清楚了,我的答案更精确了 要获取文件的内容,请执行以下操作: def read_file(filename): return open(file

我是python新手,正在使用python获取输入并编辑文件。我要编辑的值是“web iphone”,其中包含我从输入中获得的文本

迄今为止的代码:

web = raw_input("Enter value")
文件:test.py

    local {
            value web-iphone
    }

编辑:现在你的问题更清楚了,我的答案更精确了

要获取文件的内容,请执行以下操作:

def read_file(filename):
  return open(filename).read()
以及写入文件:

def write_file(filename, toWrite):
  file = open(filename, 'w')
  file.write(toWrite)
  file.close()
因此,要用用户键入的任何内容替换“web iphone”,您可以:

Web = raw_input("Enter a value ")
Replaced = read_file("myfile.txt").replace("web-iphone", Web)
write_file("myfile.txt", Replaced)
请发表评论:

newInput = raw_input("Enter a value ")
OldFile = read_file("myfile.txt")
value = OldFile.find("value"+6)
newFile = OldFile[:value] + newInput + OldFile[OldFile.find("\n",value+1):]

我是否必须覆盖文件,或者是否可以编辑文件中的文本?取决于您所说的“编辑”是什么意思-文件可以附加到,或部分可以替换,但不能插入。一般来说,您希望重写文件。我如何替换“web iphone”部分?我可以查看任何资源吗?列出了在我不知道要替换的值但我知道列的情况下编辑文件的基本方法?就像shell-awk中的“{print$2}”一样,这是可能的吗?若要替换行中的特定列?可能的话,为了格式化,我会将其添加到我答案的底部,请稍等。因为我始终希望该文件中的“值”保持不变,但希望将值后的文本更改为例如web-iphone。哦,好的。我会在一分钟内把它加到我的答案中。哦,把+6移到括号外。