본문 바로가기
python

list to txt, txt to list

by 타닥타닥 토다토닥 부부 2024. 2. 17.
반응형

list to txt, txt to list

 

list to txt

# Example list
my_list = ['item1', 'item2', 'item3', 'item4']

# Specify the file path
file_path = 'output.txt'

# Open the file in write mode
with open(file_path, 'w') as file:
    # Write each item in the list to a new line in the file
    for item in my_list:
        file.write(str(item) + '\n')

 

txt to list

# Open the text file
file_path = 'your_file.txt'

with open(file_path, 'r') as file:
    # Read the content of the file
    file_content = file.read()

    # Split the content into a list (assuming, for example, that each line contains one element)
    data_list = file_content.split('\n')

# Print the resulting list
print(data_list)

 

[참고] JavaScript (Node.js):

Copy code
const fs = require('fs');

// Sample list
const my_list = ["item1", "item2", "item3"];

// Convert the list to a string with each item on a new line
const content = my_list.join('\n');

// Write the string to a file
fs.writeFileSync('output.txt', content);
반응형

댓글