簡體   English   中英

Python編程-Os模塊-替換

[英]Python Programing - Os Module - Replace

我想要的是

我寫了一個代碼,打開一個文件(currentcode),獲取它的文本,然后在另一個文件(text.txt)中找到它,並用新的int替換currentcode。

我的密碼

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

string.replace()是字符串的方法:

https://docs.python.org/2/library/string.html#string.replace

f2中有什么? 不是字符串。 您應該閱讀文件的各行。

NameError: name 'replace' is not defined

這意味着python找不到名為“替換”的模塊,類或函數。

如果要替換文件上的文本,則需要將其內容作為字符串而不是像文件一樣的對象來獲取(就像您現在所做的那樣),然后在string上使用replace方法替換內容,最后,將內容寫入所需的文件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM