Pycharm中怎么将print的内容保存到txt文件中(语言-python)


#coding=gbk
import csv

with open("../data_all/ciyun_after.csv", "r" , encoding="utf-8") as file:
     reader = csv.reader(file)
     rows = list(reader)
     print(rows[14])
     print(rows[26])
     print(rows[55])
     print(rows[63])
     print(rows[66])
     print(rows[74])

运行结果
['清洁', '430']
['补水', '274']
['干净', '138']
['回购', '125']
['舒服', '124']
['好用', '115']

该回答引用chatgpt:


import csv

with open("../data_all/ciyun_after.csv", "r" , encoding="utf-8") as file:
    reader = csv.reader(file)
    rows = list(reader)

    with open("output.txt", "w", encoding="utf-8") as output_file:
        # 将print输出的内容写入文件
        print(rows[14], file=output_file)
        print(rows[26], file=output_file)
        print(rows[55], file=output_file)
        print(rows[63], file=output_file)
        print(rows[66], file=output_file)
        print(rows[74], file=output_file)

  • 以下回答由chatgpt基于相关博客总结生成:

    在PyCharm中将print的内容保存为txt文件,可以使用Python的文件操作来实现。

    以下是具体的步骤: 1. 定义一个函数,用于将print的内容保存到txt文件中。函数名可以是save_to_txt,函数参数可以是print的内容。 2. 在函数内部,使用with open语句打开一个txt文件,将文件对象保存到一个变量中,例如f。 3. 使用f.write方法将print的内容写入文件中,每次写入一行,可以使用\n换行。 4. 最后,使用f.close()方法关闭文件。

    以下是代码示例:

    def save_to_txt(content):
        with open("output.txt", "w") as f:
            for line in content:
                f.write(line)
                f.write("\n")
    
    content = [
        ['清洁', '430'],
        ['补水', '274'],
        ['干净', '138'],
        ['回购', '125'],
        ['舒服', '124'],
        ['好用', '115']
    ]
    
    save_to_txt(content)
    

    运行以上代码后,会在当前目录下生成一个名为output.txt的文件,其中包含了print的内容。

    希望以上步骤对解决问题有所帮助,如果有任何疑问,请随时向我提问。