在Python中,将列表内容写入文件可以通过以下几种方法实现:
1. 使用 `open` 函数和 `write` 方法:
my_list = ['apple', 'banana', 'orange']
with open('output.txt', 'w') as file:
for item in my_list:
file.write(item + '\n')
2. 使用 `writelines` 方法直接写入列表素:
l = ['A', 'B', 'C', 'D']
with open('k.txt', 'w') as file:
file.writelines(l)
3. 使用 `str` 函数将列表转化为字符串后写入:
l = ['A', 'B', 'C', 'D', 1, 2, 3]
with open('k.txt', 'w') as file:
file.write(str(l))
4. 使用 `for` 循环逐行写入列表素:
l = ['A', 'B', 'C', 'D']
with open('k.txt', 'w') as file:
for line in l:
file.write(line + '\n')
5. 使用 `join` 函数将列表素连接成一个字符串后写入:
l = ['A', 'B', 'C', 'D']
with open('k.txt', 'w') as file:
file.write('\n'.join(l))
6. 使用 `pickle` 模块将列表保存为二进制文件:
import pickle
my_list = [1, 2, 3, 4, 5]
with open('list_file.pkl', 'wb') as file:
pickle.dump(my_list, file)
7. 使用 `json` 模块将列表保存为JSON格式文件:
import json
my_list = ['apple', 'banana', 'orange']
with open('list_file.json', 'w') as file:
json.dump(my_list, file)
8. 使用 `csv` 模块将列表内容写入或更新CSV文件:
import csv
stock_file = 'stock.csv'
stock = {}
with open(stock_file, 'r') as f_stock:
csv_stock = csv.reader(f_stock, delimiter=':')
for cols in csv_stock:
stock[cols] = cols
while True:
product_code = input('Please enter product code: ')
product_quantity = int(input('Please enter quantity: '))
try:
stock[product_code] = int(stock[product_code]) + product_quantity
break
except KeyError:
print('Unknown product ID, try again')
with open(stock_file, 'w', newline='') as f_stock:
writer = csv.writer(f_stock, delimiter=':')
writer.writerows(stock.values())
选择合适的方法根据你的需求来决定
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://sigusoft.com/bj/115058.html