我想要的
我编写了一个打开文件(当前代码)的代码,获取它的文本,在另一个文件(text.txt)中找到它,并用一个新int替换当前代码。
我的密码
import os
currentcode = open('currentcode.txt','r+')
code = currentcode.read()
print('Choose File: ')
print('1: File One > ')
file = input('Enter Number Of File: ')
file = 'C:/text.txt'
old_text = code
new_text = str(int(code) + 1)
print('Opened File')
f1 = open(file, 'r')
f2 = open(file, 'w')
f2.write(replace(old_text, new_text))
currentcode.write(new_text)
f1.close()
f2.close()运行后输出
当我运行这个代码时,我得到:
Choose File:
1: File One >
Enter Number Of File: 1
Opened File
Traceback (most recent call last):
File "C:\Users\DanielandZoe\Desktop\scripys\Replace.py", line 18, in <module>
f2.write(replace(old_text, new_text))
NameError: name 'replace' is not defined发布于 2016-12-18 16:51:16
NameError: name 'replace' is not defined这意味着python找不到一个叫做“替换”的模块、类或函数。
如果要替换文件上的文本,需要将其内容作为字符串,而不是类似文件的对象(就像现在所做的那样),然后在string上使用string方法替换内容,最后,将内容写入所需的文件。
发布于 2016-12-18 16:42:03
string.replace()是用于字符串的方法:
https://docs.python.org/2/library/string.html#string.replace
f2中有什么?一根绳子也没有。你应该读文件的行。
https://stackoverflow.com/questions/41210422
复制相似问题