Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/352.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 每次将字符串写入新行上的文件_Python_Newline - Fatal编程技术网

Python 每次将字符串写入新行上的文件

Python 每次将字符串写入新行上的文件,python,newline,Python,Newline,每次调用file.write()时,我都想在字符串中添加一个换行符。在Python中,最简单的方法是什么?您可以通过两种方式来实现这一点: f.write("text to write\n") 或者,根据您的Python版本(2或3): 使用“\n”: 请参阅以供参考。您可以使用: file.write(your_string + '\n') 如果您广泛使用它(大量的书面行),您可以将“file”子类化: class cfile(file): #subclass file to ha

每次调用
file.write()
时,我都想在字符串中添加一个换行符。在Python中,最简单的方法是什么?

您可以通过两种方式来实现这一点:

f.write("text to write\n")
或者,根据您的Python版本(2或3):

使用“\n”:

请参阅以供参考。

您可以使用:

file.write(your_string + '\n')
如果您广泛使用它(大量的书面行),您可以将“file”子类化:

class cfile(file):
    #subclass file to have a more convienient use of writeline
    def __init__(self, name, mode = 'r'):
        self = file.__init__(self, name, mode)

    def wl(self, string):
        self.writelines(string + '\n')
现在,它提供了一个附加功能wl,可以满足您的需要:

fid = cfile('filename.txt', 'w')
fid.wl('appends newline charachter')
fid.wl('is written on a new line')
fid.close()

可能我缺少了一些东西,比如不同的换行符(\n,\r,…),或者最后一行也以换行符结尾,但这对我来说是有效的。

请注意,
Python 3不支持
文件
,已被删除。您可以使用
open
内置功能执行相同的操作

f = open('test.txt', 'w')
f.write('test\n')


这是我为自己解决这个问题而提出的解决方案,以便系统地生产\n作为分离器。它使用字符串列表进行写入,其中每个字符串都是文件的一行,但是它似乎也适用于您。(Python 3.+)

#获取字符串列表并将其打印到文件中。
def writeFile(文件,strList):
直线=0
行=[]
而行
您可以执行以下操作:

file.write(your_string + '\n')
正如另一个答案所建议的,但是当您可以调用
文件时,为什么要使用字符串连接(速度慢,容易出错)。请写两次:

file.write(your_string)
file.write("\n")

请注意,写入操作是缓冲的,因此它相当于相同的内容。

除非写入二进制文件,否则请使用打印。以下示例适用于格式化csv文件:

def write_row(file_, *columns):
    print(*columns, sep='\t', end='\n', file=file_)
用法:

PHI = 45
with open('file.csv', 'a+') as f:
    write_row(f, 'header', 'phi:', PHI, 'serie no. 2')
    write_row(f)  # newline
    write_row(f, data[0], data[1])
注:

  • '{},{}'。格式(1,'u second')
    -
  • '\t'-制表符
  • 函数定义中的
    *列
    -将任意数量的参数分派到列表中-请参阅

另一种使用fstring从列表写入的解决方案

lines = ['hello','world']
with open('filename.txt', "w") as fhandle:
  for line in lines:
    fhandle.write(f'{line}\n')
作为一种功能

def write_list(fname, lines):
    with open(fname, "w") as fhandle:
      for line in lines:
        fhandle.write(f'{line}\n')

write_list('filename.txt', ['hello','world'])

我真的不想每次都键入
\n
,而且似乎对我不起作用,所以我创建了自己的类

class文件():
定义初始化(self,name,mode='w'):
self.f=open(名称、模式、缓冲=1)
def write(self,string,换行符=True):
如果换行:
self.f.write(字符串+“\n”)
其他:
self.f.write(字符串)
在这里它被实现了

f=File('console.log')
f、 写入('这在第一行')
f、 write('这在第二行',换行符=False)
f、 写入('这仍然在第二行')
f、 写入('这在第三行')
这应该在日志文件中显示为

这在第一行
这是第二行这还是第二行
这是第三线

好的,这里有一个安全的方法

with open('example.txt', 'w') as f:
 for i in range(10):
  f.write(str(i+1))
  f.write('\n')



这会在新行中写入1到10个数字。

您可以在需要此行为的特定位置写入方法:

#Changed behavior is localized to single place.
with open('test1.txt', 'w') as file:    
    def decorate_with_new_line(method):
        def decorated(text):
            method(f'{text}\n')
        return decorated
    file.write = decorate_with_new_line(file.write)
    
    file.write('This will be on line 1')
    file.write('This will be on line 2')
    file.write('This will be on line 3')

#Standard behavior is not affected. No class was modified.
with open('test2.txt', 'w') as file:
        
    file.write('This will be on line 1')
    file.write('This will be on line 1')
    file.write('This will be on line 1')  
print()
语句上使用
append(a)
open()
看起来更容易:

save_url  = ".\test.txt"

your_text = "This will be on line 1"
print(your_text, file=open(save_url, "a+"))

another_text = "This will be on line 2"
print(another_text, file=open(save_url, "a+"))

another_text = "This will be on line 3"
print(another_text, file=open(save_url, "a+"))

我正在使用f.writelines(str(x))写入一个文件,其中x是list,现在告诉您如何将一个列表x写入一个文件中,从新开始处理每个列表line@kaushik:f.write('\n'.join(x))或f.writelines(i+'\n'表示x中的i)我认为f.write方法更好,因为它可以在Python 2和3中使用。您可以使用这种用法,例如,将int写入文件时,可以使用file.write(str(a)+'\n')@xikhari为什么
file.write(f“我的号码是:{number}\n”)
很好,可读性很好。以“a”作为参数而不是“w”打开文件不会改变write to函数以您描述的方式工作。它唯一的作用是不会覆盖文件,文本将添加到最下面的一行,而不是从空白文件的左上角开始。如果使用变量来组成记录,则可以在末尾添加+“\n”,如fileLog.write(var1+var2+“\n”)。在较新版本的Python(3.6+)中您也可以只使用f-strings:
file.write(f{var1}\n”)
或带有单引号的file.write(f{var1}\n')。在这种情况下,您不需要
返回None
,因为首先,您不需要它,其次,当没有
return
语句时,默认情况下每个Python函数都返回
None
。这是一个很好的解决方案,老实说
file
应该将其作为参数,在文件打开时应用。为什么不简单地将open(path,“w”)作为file:for strList中的行使用
:file.write(line+“\n”)
?这样,您可以删除所有列表工作、检查,并且只有3行。
lines = ['hello','world']
with open('filename.txt', "w") as fhandle:
  for line in lines:
    fhandle.write(f'{line}\n')
def write_list(fname, lines):
    with open(fname, "w") as fhandle:
      for line in lines:
        fhandle.write(f'{line}\n')

write_list('filename.txt', ['hello','world'])
with open('example.txt', 'w') as f:
 for i in range(10):
  f.write(str(i+1))
  f.write('\n')


#Changed behavior is localized to single place.
with open('test1.txt', 'w') as file:    
    def decorate_with_new_line(method):
        def decorated(text):
            method(f'{text}\n')
        return decorated
    file.write = decorate_with_new_line(file.write)
    
    file.write('This will be on line 1')
    file.write('This will be on line 2')
    file.write('This will be on line 3')

#Standard behavior is not affected. No class was modified.
with open('test2.txt', 'w') as file:
        
    file.write('This will be on line 1')
    file.write('This will be on line 1')
    file.write('This will be on line 1')  
save_url  = ".\test.txt"

your_text = "This will be on line 1"
print(your_text, file=open(save_url, "a+"))

another_text = "This will be on line 2"
print(another_text, file=open(save_url, "a+"))

another_text = "This will be on line 3"
print(another_text, file=open(save_url, "a+"))