列表和字符串格式化困难:导入txt文件,添加字符串并将其写入新文件

问题描述:

我遇到列表和字符串格式问题,并将更改写入新文件。我正在寻找的是:列表和字符串格式化困难:导入txt文件,添加字符串并将其写入新文件

  1. 字串之前,
  2. 导入txt文件的内容(字符串值的列表)
  3. STRINGS后

凡前面和后面都STRINGS已经定义,并且所有内容都写入一个新文件!

我的最终目标是当我导入一个txt文件(包含一个列表)并运行代码时,它将被打印到一个新文件,其中包含在导入的txt文件列表之前和之后添加的预定义字符串。

我的代码现在如下:现在

text_file = open(r"text_file path", "r") 
lines = text_file.read().split(',') 
lines.insert(0, "String Values Before") 
lines.insert("String Values After") 
text_file.close() 
lines.write("new_file.txt", "w+") 

的问题是,我插入到列表中,而我想要的字符串是单独的名单!

我已经能够生产什么我想要的书面文件,看起来像在控制台中使用此代码在这里:

FIRMNAME = "apple" 
FILETYPE = "apple" 
REPLYFILENAME = "apple" 
SECMASTER = "apple" 
PROGRAMNAME = "apple" 

text_file = open(r"textfile path", "r+") 
lines = text_file.readlines().split('\n') 

print(("START-OF-FILE \nFIRMNAME= ") + FIRMNAME) 

print(("FILETYPE= ") + FILETYPE) 

print(("REPLYFILENAME= ") + REPLYFILENAME) 

print(("SECMASTER= ") + SECMASTER) 

print(("PROGRAMNAME= ") + PROGRAMNAME) 


print("START-OF-FIELDS") 

print("END-OF-FIELDS") 

print("START-OF-DATA") 
pprint.pprint(lines) 
print("END-OF-DATA") 
print("END-OF-FILE") 

我只是无法弄清楚如何写这个到一个新文件!帮帮我!

+0

使用追加模式和换行符 –

+0

你是什么意思呢?可以展示给我吗?谢谢! :) –

+1

'lines.write(“new_file.txt”,“a”)' –

你可以解决这个问题是这样的:

newFile = 'your_new_file.txt' 
oldFile = 'your_old_file.txt' 

# Open the new text file 
with open(newFile, 'w') as new_file: 
    # Open the old text file 
    with open(oldFile, 'r') as old_file: 
     # Write the line before the old content 
     new_file.write('Line before old content\n') 

     # Write old content 
     for line in old_file.readlines(): 
      new_file.write(line) 

     # Write line after old content 
     new_file.write('Line after old content') 
+1

谢谢mischi!有效! :) –

你的变量lineslist类型,它没有一个方法write的。
此外insert需要一个位置,你的第二个电话缺乏。

您需要使用相应的前缀和后缀值读取该文件,CONCAT,然后将其写入适当的输出文件:

with open("text_file_path", "r") as input_file: 
    text = input_file.read() 

text = '\n'.join(("String Values Before", text, "String Values After")) 

with open("new_file.txt", "w+") as output_file: 
    output_file.write(text) 

使用pformat
pprint

before_values = ["a", "b", "c"] 
data = ["1", "2", "3"] 
after_values = ["d", "e", "f"] 
with open("outfile.txt", "w) as outfile: 
    outfile.write("\n".join(before_values)) # Write before values 
    outfile.write(pprint.pformat(data))  # Write data list 
    outfile.write("\n".join(after_values)) # Write after values 

你有一个错误,你最初调用insert方法,你必须提供一个指标;但是,你可以添加,合并产生的列表,并写入文件:

text_file = open(r"text_file path", "r") 
lines = text_file.read().split(',') 
lines.insert(0, "String Values Before") 
lines.append("String Values After") 
text_file.close() 
new_file = open('text_file_path.txt', 'w') 
new_file.write(','.join(lines)+'\n') 
new_file.close()