Think before you speak, read before you think.

python文件读写

python写文件

object_id_list=[1, 3, 88, 99]

f=open('mylist', "w”)

for id in object_id_list:

    f.writelines(str(id))

f.close()   #只有输入这一句之后才会真正写入到文件中

cat mylist

有换行的时候

138899%   # 最后有一个%表示没有换行
>>> object_id_list=[1, 3, 88, 99]
>>> f=open('mylist', "w")
>>> for id in object_id_list:
...     f.writelines(str(id) + '\n')    # 换行
...
>>> f.close()

➜  ~  cat mylist

1
3
88
99

python读取json文件

文件格式如下

{
    "object_id": 430,
    "type": 23
}
object_id_read = open(object_id_file, "r")
object_id_file_json = ''
for line in object_id_read:
    object_id_file_json = object_id_file_json + line.strip('\n')
data = json.loads(object_id_file_json)
object_id = data['object_id']

f.write 和 f.writelines有什么区别?

f.read()
f.readline()
f.readlines()


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *