Python clears the file and replaces the content, json loads and dumps use attention points

  • There is a text file, you need to replace a word in it, and use python to complete it. I wrote it like this:
def modify_text():
    with open('test.txt', "r+") as f:
        read_data = f.read()
        f.truncate()   #清空文件
        f.write(read_data.replace('apple', 'android'))

Execute the above function, it will append the content instead of replacing it.
f.truncate() doesn't work, how should I write it?
You need to add f.seek(0) to locate the file to position 0. Without this sentence, the file is positioned to the end of the data, and truncate is also deleted from here, so it feels like it doesn't work.

def modify_text():
    with open('test.txt', "r+") as f:
        read_data = f.read()
        f.seek(0)
        f.truncate()   #清空文件
        f.write(read_data.replace('apple', 'android'))
  • Points to note when using json loads and dumps

Among them, json.dumps serializes json into a string, and json supports the basic data format of int, str, and bool. If we use int as keys, the keys will be changed to str type during dumps. Json.loads is also str type. Therefore, all keys need to be changed to str for standardization.

test:

aa=json.dumps(price_center_mean_feature_list)
print(aa)
print(type(aa))
> {
    
    "300": [{
    
    "0": .....
aa=json.dumps(price_center_mean_feature_list)
print(aa)
print(type(aa))
> {
    
    "300": [{
    
    "0": 
> <class 'str'>
aa=json.dumps(price_center_mean_feature_list)
print(aa)
print(type(aa))
> {
    
    "300": [{
    
    "0": 
> <class 'dict'>

Guess you like

Origin blog.csdn.net/yangdashi888/article/details/103742278