在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)
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())
选择合适的方法根据你的需求来决定