file.write()ฉันต้องการที่จะผนวกการขึ้นบรรทัดใหม่ให้สตริงของฉันทุกเวลาที่ผมเรียก วิธีที่ง่ายที่สุดในการทำสิ่งนี้ใน Python คืออะไร?
file.write()ฉันต้องการที่จะผนวกการขึ้นบรรทัดใหม่ให้สตริงของฉันทุกเวลาที่ผมเรียก วิธีที่ง่ายที่สุดในการทำสิ่งนี้ใน Python คืออะไร?
คำตอบ:
file.write(f"{var1}\n")
                    คุณสามารถทำได้สองวิธี:
f.write("text to write\n")หรือขึ้นอยู่กับเวอร์ชัน Python ของคุณ (2 หรือ 3):
print >>f, "text to write"         # Python 2.x
print("text to write", file=f)     # Python 3.xคุณสามารถใช้ได้:
file.write(your_string + '\n')file.write(f"my number is: {number}\n")ทำได้ดีและอ่านง่าย
                    ถ้าคุณใช้มันอย่างกว้างขวาง (เป็นจำนวนมากเขียนบรรทัด) คุณสามารถ subclass '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, ... ) หรือว่าบรรทัดสุดท้ายก็ถูกยกเลิกด้วยการขึ้นบรรทัดใหม่ แต่ก็ใช้งานได้สำหรับฉัน
return Noneในกรณีนี้เพราะก่อนอื่นคุณไม่จำเป็นต้องใช้และอย่างที่สองฟังก์ชั่น Python ทุกตัวจะคืนค่าNoneตามค่าเริ่มต้นเมื่อไม่มีreturnคำสั่ง
                    คุณสามารถทำได้:
file.write(your_string + '\n')ตามที่แนะนำโดยคำตอบอื่น แต่เหตุใดการใช้การต่อสตริง (ช้าผิดพลาดได้ง่าย) เมื่อคุณสามารถโทรหาfile.writeสองครั้ง:
file.write(your_string)
file.write("\n")โปรดทราบว่าการเขียนถูกบัฟเฟอร์ดังนั้นจึงมีจำนวนเท่ากับสิ่งเดียวกัน
file_path = "/path/to/yourfile.txt"
with open(file_path, 'a') as file:
    file.write("This will be added to the next line\n")หรือ
log_file = open('log.txt', 'a')
log_file.write("This will be added to the next line\n")เพียงแค่บันทึกfileไม่ได้รับการสนับสนุนPython 3และถูกลบออก คุณสามารถทำเช่นเดียวกันกับopenฟังก์ชั่นในตัว
f = open('test.txt', 'w')
f.write('test\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])หมายเหตุ:
'{}, {}'.format(1, 'the_second')- https://pyformat.info/ , PEP-3101*columnsในการกำหนดฟังก์ชั่น - แจกจ่ายจำนวนของข้อโต้แย้งใด ๆ ในรายการ - ดูคำถามเกี่ยวกับ * args & ** kwargsโซลูชันอื่นที่เขียนจากรายการโดยใช้ fstring
lines = ['hello','world']
with open('filename.txt', "w") as fhandle:
  for line in lines:
    fhandle.write(f'{line}\n')นี่คือทางออกที่ฉันพยายามแก้ไขปัญหานี้ให้กับตัวเองเพื่อสร้าง \ n เป็นตัวแยกอย่างเป็นระบบ มันเขียนโดยใช้รายการของสตริงที่แต่ละสตริงเป็นหนึ่งบรรทัดของไฟล์อย่างไรก็ตามดูเหมือนว่ามันจะทำงานให้คุณเช่นกัน (Python 3 +)
#Takes a list of strings and prints it to a file.
def writeFile(file, strList):
    line = 0
    lines = []
    while line < len(strList):
        lines.append(cheekyNew(line) + strList[line])
        line += 1
    file = open(file, "w")
    file.writelines(lines)
    file.close()
#Returns "\n" if the int entered isn't zero, otherwise "".
def cheekyNew(line):
    if line != 0:
        return "\n"
    return ""with open(path, "w") as file: for line in strList: file.write(line + "\n")? วิธีนี้คุณสามารถลบรายการงานทั้งหมดการตรวจสอบและมีเพียง 3 บรรทัด