简体   繁体   English

Python从文件中读取 - 换行

[英]Python read from file - newline

I am writing a list (simple[]) to a file using writelines() and I need each item from the list to be on a new line in the file.我正在使用 writelines() 将列表 (simple[]) 写入文件,我需要列表中的每个项目都在文件中的新行上。 I am using the following code:我正在使用以下代码:

file_path_simple = r'[path_redacted]\tx_list_simple.txt'
    with open(file_path_simple, 'w') as fp:
        for i in simple:
            #ignores any blank lines
            if i == '':
                continue
            else:
                fp.writelines([i])
                fp.writelines('\n')
        fp.close()

The problem I am having is that when read from the file later it includes the \n, so instead of python reading:我遇到的问题是,稍后从文件中读取时它包含 \n,因此不是 python 读取:

blablabla

it reads:上面写着:

blablabla\n

How can I make it not read the \n?我怎样才能让它不读\n? Or do I need to use something like re.split() to remove the \n prior to reading?或者我是否需要在阅读之前使用 re.split() 之类的东西来删除 \n ?

This seems like something really simple I am overlooking.这似乎是我忽略的非常简单的事情。

You can use rstrip .您可以使用rstrip

i = i.rstrip('\n')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从Python中的任意换行符开始的文件中读取行 - How to read lines from file starting from arbitrary newline in Python 如何从python文件中读取行并从其中删除换行符? - How to read lines from a file in python and remove the newline character from it? 如何使用Python ConfigParser从配置文件读取换行符 - How to read a newline from config file using Python ConfigParser python读取带有块的文件,但以换行符结尾(\\ n) - python read file with block, but end with newline(\n) 如何使用Python有效地读取带有自定义换行符的大文件? - How to efficiently read a large file with a custom newline character using Python? 如何读取python中的文件,其中包含换行符和制表符? - How to read a file in python which has newline and tabs into a string? Python读取带有换行符和段落分隔元素的文本文件 - Python read text file with newline and and paragraph separated elements 有没有办法使用换行符以外的分隔符在python中循环读取文件 - Is there a way to read a file in a loop in python using a separator other than newline Python 如何使用换行符读取字典文件? - Python how can I read file of dictionaries with newline? 如何在python中存储或读取yaml中的文字回车符和换行符 - How to store or read a literal carriage return and newline from yaml in python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM